// 服务端程序
// 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.