UNIX网络编程练习-获取客户端IP和端口
2015-11-30 14:13
489 查看
// 服务端程序 // DATE: 2015.11.30 // AUTH: robertkun #include <netinet/in.h> #include <sys/socket.h> #include <sys/types.h> #include <arpa/inet.h> #include <stdlib.h> #include <stdio.h> #include <iostream> #include <string.h> #include <unistd.h> #include <errno.h> using namespace std; typedef struct sockaddr SA; int main() { char buff[256] = {0}; // 创建TCP套接字 int _fd = socket(AF_INET, SOCK_STREAM, 0); // 绑定端口到套接字 struct sockaddr_in addr; bzero(&addr, sizeof(addr)); addr.sin_family = AF_INET; addr.sin_addr.s_addr = htonl(INADDR_ANY); addr.sin_port = htons(6543); if(bind(_fd, (SA *)&addr, sizeof(addr)) != 0) { cerr<<"bind error!"<<errno<<endl; return -1; } // 打开监听 if(listen(_fd, 256) != 0) { cerr<<"listen error!"<<endl; return -1; } // 等待连接 while(1) { struct sockaddr_in c_addr; socklen_t c_len = sizeof(c_addr); // 这里必须初始化,才可以使用 int _connfd = accept(_fd, (SA *)&c_addr, &c_len); if(_connfd) { // 获取客户端信息,也可以使用getpeername()函数 //getpeername(_connfd, (SA *)&c_addr, &c_len); cout<<"accept ok! "<<"client = "<<inet_ntoa(c_addr.sin_addr) <<":"<<ntohs(c_addr.sin_port)<<endl; } time_t ticks = time(NULL); snprintf(buff, sizeof(buff), "%.24s\r\n", ctime(&ticks)); write(_connfd, buff, strlen(buff)); // 终止连接 close(_connfd); } return 0; }
输出:
man accept:
The addrlen argument is a value-result argument:
the caller must initialize it to contain the size (in bytes) of the structure pointed to by addr;
on return it will contain the actual size of the peer address.
相关文章推荐
- 微信支付认证和ssl-https
- iOS 数据库离线缓存思路和网络层封装
- ubunut无法连接有线网络上网,在windows下可以连接网络
- Android OkHttp完全解析
- VMware网络连接的三种模式
- HTTP协议处理流程
- HTTP状态码详解
- c++ http请求
- http协议
- Python实现单隐层神经网络
- Http协议中的方法
- OSSIM让网络***无所遁形
- OSSIM让网络攻击无所遁形
- 使用网络编程的较好方式
- IPv4网络地址与子网划分
- OpenFlow对网络创新的影响
- iOS 保持界面流畅的技巧(转自http://blog.ibireme.com/author/ibireme/)
- IOS学习之 网络编程(6)--文件上传
- ios9 http请求不通。修改plist文件也不行的状况
- Mac OS X 跟新到10.11后cocoapods安装出现的问题(- bad response Not Found 404 (http://ruby.taobao.org/latest_spe)