- 论坛徽章:
- 0
|
写了一个服务器端/客户端的socket程序。在本机上测试,运行正常。
有一个不明白的地方:我客户端连接的地址是127.0.0.1,但是服务器端读出来的时候,第一次不是127.0.0.1,。具体可见下面的输出信息:
服务器端代码:
- #include <stdio.h>
- #include <stdlib.h>
- #include <unistd.h>
- #include <ctype.h>
- #include <sys/socket.h>
- #include <arpa/inet.h>
- #include <string.h>
- #define MAX_LINE 200
- void my_fun(char * p)
- {
- if(p == NULL)
- return;
- for (; *p != '\0'; p++)
- if(*p >= 'A' && *p <= 'Z')
- *p = *p -'A'+ 'a';
- }
- int main(void)
- {
- struct sockaddr_in sin;
- struct sockaddr_in cin;
- int l_fd;
- int c_fd;
- socklen_t len;
- char buf[MAX_LINE];
- char savebuf[200];
- char addr_p[INET_ADDRSTRLEN];
- int port = 8000;
- int n;
- bzero(&sin, sizeof(sin));
- sin.sin_family = AF_INET;
- sin.sin_addr.s_addr = INADDR_ANY;
- sin.sin_port = htons(port);
-
- l_fd = socket(AF_INET, SOCK_STREAM, 0);
-
- bind(l_fd, (struct sockaddr *)&sin, sizeof(sin));
-
- listen(l_fd, 10);
-
- printf("waiting ...\n");
-
- while(1)
- {
- c_fd = accept(l_fd, (struct sockaddr *) &cin, &len);
- n = read(c_fd, buf, MAX_LINE);
- inet_ntop(AF_INET, &cin.sin_addr, addr_p, sizeof(addr_p));
- printf("client IP is %s, port is %d\n", addr_p, ntohs(sin.sin_port));
- printf("buf:%s \n",buf);
- my_fun(buf);
- write(c_fd, buf, n);
- close(c_fd);
- }
- if(close(l_fd) == -1){
- perror("fail to close");
- exit(1);
- }
- return 0;
- }
复制代码 客户端代码:
- #include <stdio.h>
- #include <unistd.h>
- #include <sys/types.h>
- #include <sys/socket.h>
- #include <arpa/inet.h>
- #include <string.h>
- #define MAX_LINE 200
- int main(int argc, char *argv[])
- {
- struct sockaddr_in sin;
- char buf[MAX_LINE];
- int sfd;
- int port = 8000;
- char *str = "TEST STRING";
- if (argc > 1)
- str = argv[1];
- bzero(&sin, sizeof(sin));
- sin.sin_family = AF_INET;
- inet_pton(AF_INET, "127.0.0.1", &sin.sin_addr);
- sin.sin_port = htons(port);
- sfd = socket(AF_INET, SOCK_STREAM, 0);
- connect(sfd, (struct sockaddr_in *)&sin, sizeof(sin));
- write(sfd, str, strlen(str) + 1);
- read(sfd, buf, MAX_LINE);
- printf("recive from server: %s\n", buf);
- close(sfd);
- return 0;
- }
复制代码 程序输入输出信息:- input:
- [root@localhost 2]# ./client "wwwwwwww"
- recive from server: wwwwwwww
- [root@localhost 2]# ./client "wwwwwwww"
- recive from server: wwwwwwww
- [root@localhost 2]# ./client "wwwwwwww"
- recive from server: wwwwwwww
- [root@localhost 2]# ./client "wwwwwwww"
- recive from server: wwwwwwww
- output:
- [root@localhost 2]# ./server
- waiting ...
- client IP is 56.249.234.191, port is 8000 //为什么这里得到的IP不是127.0.0.1
- buf:wwwwwwww
- client IP is 127.0.0.1, port is 8000
- buf:wwwwwwww
- client IP is 127.0.0.1, port is 8000
- buf:wwwwwwww
- client IP is 127.0.0.1, port is 8000
- buf:wwwwwwww
复制代码 |
|