#include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/types.h> #include <sys/socket.h> #include <arpa/inet.h> #include <unistd.h> #include <pthread.h> #include <errno.h> #define DAEMON_PORT 8888 #define MAX_LISTEN 1024 ]; int adminserver(); void pthread_adminserver(int client_sd); int main(int argc, char** argv){ strcpy(get_manager_ip, argv[]); adminserver(); } int adminserver() { ; ; ; ; FILE *fp; int res; int client_sd; int server_sd; int reuse_addr; pthread_t p_tcpserver; int client_addr_size ; struct sockaddr_in client_addr; struct sockaddr_in server_addr; ]; ]; ]; char *pt; char *edit; sprintf(cmd_ip,"ifconfig %s |grep 'addr:' >/get_manager_ip",get_manager_ip); system(cmd_ip); fp = fopen("/get_manager_ip","rb"); if (fp == NULL) { printf("Cann't open get_manger_ip file!\n"); exit(-); } memset(line,,); fgets(line,,fp); fclose(fp); pt=strstr(line, "addr:"); if (pt != NULL) { pt+=; edit=strtok(pt," "); strcpy(listen_ip,edit); } server_sd=socket( AF_INET, SOCK_STREAM, ); ) { printf("ERROR: Cann't create socket!!!\n"); exit(-); } bzero(&server_addr, sizeof(struct sockaddr)); server_addr.sin_family = AF_INET; server_addr.sin_addr.s_addr=inet_addr(listen_ip); server_addr.sin_port = htons(DAEMON_PORT); reuse_addr = ; ) { printf("setsockopt error\n"); close(server_sd); ; } res = bind(server_sd, (struct sockaddr *)&server_addr, sizeof(server_addr)); ) { printf("Cann't bind!res = %d,erro:%d, reason:%s.\n",res, errno, strerror(errno)); close(server_sd); exit(-); } ) { printf("Cann't listen!\n"); close(server_sd); exit(-); } ) { client_addr_size = sizeof(client_addr); client_sd = accept( server_sd, (struct sockaddr *)&client_addr, (socklen_t *)&client_addr_size); ) { printf("Could not create thread check_work_time\n"); return ; } } close(server_sd); exit(); } void pthread_adminserver(int client_sd) { ; int rc; ]; ) { //线程处理某个客户端的连接 memset(buffer,,); rc=read(client_sd,buffer,); ){ close(client_sd); //关闭线程处理的客户端连接 pthread_exit();//终止该线程 } printf("read date:\"%s\"\n",buffer); } close(client_sd); //关闭线程处理的客户端连接 pthread_exit();//终止该线程 }
通过线程去处理单条tcp连接,传入网卡名来获取本地所需使用的ip地址,(不同的linux系统需要做点修改,在查询关键字 “addr:”处)