socket 地址问题请教
时间:2010-07-19
来源:互联网
本帖最后由 peijue 于 2010-07-19 15:58 编辑
server.h文件
复制代码
为什么同一个IP连接过来 打印出来的IP都不一样呢?
复制代码
各位帮帮忙;
得到的IP都是这样的。
复制代码
server.h文件
- #include <sys/types.h>
- #include <pthread.h>
- #include <sys/socket.h>
- #include <netdb.h>
- #include <stdlib.h>
- #include <stdio.h>
- #include <netinet/in.h>
- #include <fcntl.h>
- #include <arpa/inet.h>
- #define SERVER_PORT 48888 /*定义通信端口 */
- #define BUF_SIZE 4096 /*定义传输数据的大小*/
- #define QUEUE_SIZE 10 /* 定义最大连接数 */
-
- void *work_thread(void *c)
- {
- int sockfd = (int)c;
- printf("thread id : %u\n", pthread_self() );
- int fd, l;
- char buf[BUF_SIZE];
- l = recv(sockfd, buf, BUF_SIZE, 0);
- printf("%s\n", buf);
- if( l == -1) perror("l");
- fd = open(buf, O_RDONLY);
- if( fd < 0 )
- {
- printf("open file fail: %s\n", buf);
- sprintf(buf, "%s", "not the file in server\n");
- send(sockfd, buf, strlen(buf)+1, 0);
- close(sockfd);
- return (void *)1;
- }
- while(1)
- {
- l = read(fd, buf, BUF_SIZE);
- if( l <= 0 ) break;
- send(sockfd, buf, l, 0);
- }
- printf("send file success\n");
- close(fd);
- close(sockfd);
- return (void *)1;
- }
-
- int main( int argc, char *argv[] )
- {
- int b, s, l, sa, fd, bytes, on = 1;
- char buf[ BUF_SIZE ]; /*发送文件的缓冲区*/
- struct sockaddr_in channel, addr_c; /* 控制IP 地址的结构 */
-
- /*--初始化套接字地址结构--*/
- memset(&channel, 0, sizeof(struct sockaddr_in ) );
- channel.sin_family = AF_INET;
- channel.sin_addr.s_addr = htonl( INADDR_ANY );
- channel.sin_port = htons( SERVER_PORT );
-
-
- /*--创建套接字等待连接--*/
-
- s = socket( AF_INET, SOCK_STREAM, IPPROTO_TCP );
- if( s < 0 ) perror("s");
- setsockopt( s, SOL_SOCKET, SO_REUSEADDR, (char *)&on, sizeof(on) );
-
- b = bind( s, (struct sockaddr *)&channel, sizeof(channel) );
- if( b < 0) perror("b");
-
- l = listen( s, QUEUE_SIZE );
- int len = sizeof(struct sockaddr_in);
- if( l < 0) perror("l");
- /* 等待连接到来,并处理连接请求*/
- while(1)
- {
- int err;
- char ip[INET_ADDRSTRLEN];
- sa = accept( s, (struct sockaddr *)&addr_c, &len );/*接受一个套接字的请求*/
- if( sa < 0)
- perror("sa");
- inet_ntop(AF_INET, &addr_c, ip, INET_ADDRSTRLEN);
- printf("\n%s\n", ip );
- pthread_t tid;
- err = pthread_create(&tid, NULL, work_thread, (void *)sa);
- if(err != 0)
- {
- printf("create thread failed");
- exit(1);
- }
-
- }
-
- }
- inet_ntop(AF_INET, &addr_c, ip, INET_ADDRSTRLEN);
- printf("\n%s\n", ip );
得到的IP都是这样的。
- 2.0.134.51
- thread id : 3029031792
- test.c
- send file success
-
- 2.0.134.52
- thread id : 3020639088
- test.c
- send file success
作者: peijue 发布时间: 2010-07-19
请问,服务器怎么实现relay,我的想法是把每个客户端的连接的IP地址记录下来,存放在一个表里,然后发送信息的一方发送内容里带接收方的IP地址,然后进行转发,可是我这样接受过来的IP地址是不一样的
作者: peijue 发布时间: 2010-07-20
相关阅读 更多
热门阅读
-
office 2019专业增强版最新2021版激活秘钥/序列号/激活码推荐 附激活工具
阅读:74
-
如何安装mysql8.0
阅读:31
-
Word快速设置标题样式步骤详解
阅读:28
-
20+道必知必会的Vue面试题(附答案解析)
阅读:37
-
HTML如何制作表单
阅读:22
-
百词斩可以改天数吗?当然可以,4个步骤轻松修改天数!
阅读:31
-
ET文件格式和XLS格式文件之间如何转化?
阅读:24
-
react和vue的区别及优缺点是什么
阅读:121
-
支付宝人脸识别如何关闭?
阅读:21
-
腾讯微云怎么修改照片或视频备份路径?
阅读:28