一个简单socket程序问题
就是客户端发送字符串服务端进行大小写转换,把结果显示出来,但显示结果有问题,没有转换成功,原样传回来了,显示客户端口也出现问题,端口号是8000,显示出来却是59363,请大家指教一下!谢谢!
waiting ...
client IP is 127.0.0.1, port is 59363
client is : Test String
receive from server: Test String
server.c
1 #include <stdio.h>
2 #include <stdlib.h>
3 #include <netdb.h>
4 #include <arpa/inet.h>
5 #include <unistd.h>
6 #include <sys/socket.h>
7 #include <ctype.h>
8
9 #define MAX_LINE 100
10
11 void my_fun(char * p)
12 {
13 if(p == NULL)
14 return;
15
16 for(; *p != '\0'; p ++)
17 if(*p >= 'A' && p <= 'Z')
18 *p = *p - 'A' + 'a';
19 }
20
21 int main(void)
22 {
23 struct sockaddr_in sin;
24 struct sockaddr_in cin;
25 int l_fd;
26 int c_fd;
27 socklen_t len;
28 char buf[MAX_LINE];
29 char addr_p[INET_ADDRSTRLEN];
30 int port = 8000;
31 int n;
32
33 bzero(&sin, sizeof(sin));
34 sin.sin_family = AF_INET;
35 sin.sin_addr.s_addr = INADDR_ANY;
36 sin.sin_port = htons(port);
37
38 l_fd = socket(AF_INET, SOCK_STREAM, 0);
39
40 bind(l_fd, (struct sockaddr *)&sin, sizeof(sin));
41
42 listen(l_fd,10);
43
44 printf("waiting ...\n");
45
46 while(1)
47 {
48 c_fd = accept(l_fd, (struct sockaddr *)&cin, &len);
49
50 n = read(c_fd, buf, MAX_LINE);
51
52 inet_ntop(AF_INET, &cin.sin_addr, addr_p, sizeof(addr_p));
53
54 printf("client IP is %s, port is %d\n", addr_p, ntohs(cin.sin_port));
55
56 printf("client is : %s\n", buf);
57
58 my_fun(buf);
59
60 write(c_fd, buf, n);
61
62 close(c_fd);
63
64 }
65
66 if(close(l_fd) == -1)
67 {
68 perror("fail to close");
69 exit(1);
70 }
71
72 return 0;
73
74 }
74,1 Bot
client.c
1 #include <stdio.h>
2 #include <stdlib.h>
3 #include <arpa/inet.h>
4 #include <unistd.h>
5 #include <sys/socket.h>
6
7 #define MAX_LINE 100
8
9 int main(int argc, char **argv)
10 {
11 struct sockaddr_in sin;
12 int sfd;
13 char buf[MAX_LINE];
14 int port = 8000;
15 char *str = "Test String";
16
17 if(argc > 1)
18 str = argv[1];
19
20 bzero(&sin, sizeof(sin));
21 sin.sin_family = AF_INET;
22 sin.sin_port = htons(port);
23 inet_pton(AF_INET, "127.0.0.1", &sin.sin_addr);
24
25 sfd = socket(AF_INET, SOCK_STREAM, 0);
26
27 connect(sfd, (struct sockaddr_in *)&sin, sizeof(sin));
28
29 write(sfd, str, strlen(str) + 1);
30
31 read(sfd, buf, MAX_LINE);
32
33 printf("receive from server: %s\n", buf);
34
35 close(sfd);
36
37 return 0;
38
}