Source Code For TCP Server
Source Code For TCP Server
1 /*************************************************************************************/
2 /* C program to implemet TCP Server*/
3 /* Download more programs at http://sourcecode4u.com/ */
4 /*************************************************************************************/
5 #include <stdio.h>
6 #include <sys/socket.h>
7 #include <sys/types.h>
8 #include <arpa/inet.h>
9 #include <string.h>
10int main(void)
11 {
12int s, len;
13char buf[BUFSIZ];
14struct sockaddr_in remote_addr;
15memset(&remote_addr, 0, sizeof(remote_addr));
16remote_addr.sin_family = AF_INET;
17remote_addr.sin_addr.s_addr = inet_addr(127.0.0.1);
18remote_addr.sin_port = htons(8000);
19if( (s = socket(AF_INET, SOCK_STREAM, 0)) < 0)
20{
21printf(Error\n);
22return -1;
23}
24if( connect(s, (struct sockaddr*)&remote_addr, sizeof(struct sockaddr)) < 0 )
25{
26printf(Error\n);
27return -1;
28}
29printf(Connection established\n);
30len = recv(s, buf, BUFSIZ, 0);
31buf[len] = ;
32printf(%s\n, buf);
33while(1)
34{
35printf(Enter text: );
36scanf(%s%, buf);
37if( !strcmp(buf, quit) )
38break;
39len = send(s, buf, strlen(buf), 0);
40len = recv(s, buf, BUFSIZ, 0);
41buf[len] = ;
42printf(From server: %s\n, buf);
43}
44close(s);
45return 0;
46}
7 #include <sys/types.h>
8 #include <arpa/inet.h>
9 #include <string.h>
10int main(void)
11 {
12char buf[BUFSIZ], ubuf[BUFSIZ];
13int s, fd, len;
14int sin_size;
15struct sockaddr_in my_addr;
16struct sockaddr_in remote_addr;
17memset(&my_addr, 0, sizeof(my_addr));
18my_addr.sin_family = AF_INET;
19my_addr.sin_addr.s_addr = INADDR_ANY;
20my_addr.sin_port = htons(8000);
21if( (s = socket(AF_INET, SOCK_STREAM, 0)) < 0)
22{
23printf("Error\n");
24return -1;
25}
26if( bind(s, (struct sockaddr*)&my_addr, sizeof(struct sockaddr)) < 0)
27{
28printf("Error\n");
29return -1;
30}
31listen(s, 6);
32sin_size = sizeof(struct sockaddr_in);
33if( (fd = accept(s, (struct sockaddr*)&remote_addr, &sin_size)) < 0 )
34{
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
buf[len] = '';
buf[0] = toupper(buf[0]);
send(fd, buf, len, 0);
}
close(fd);
close(s);
return 0;
}