threadserver.c
#include<stdio.h>
#include<unistd.h>
#include<stdlib.h>
#include<string.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#include<pthread.h>
struct Arg
{
int fd;
struct sockaddr_in client;
};
void *function(void *arg);
int main()
{
int listen_fd;
int conn_fd;
struct sockaddr_in server;
struct sockaddr_in client1;
listen_fd = socket(AF_INET,SOCK_STREAM,0);
if(listen_fd < 0)
{
perror("socket");
return -1;
}
int opt = SO_REUSEADDR;
setsockopt(listen_fd,SOL_SOCKET,SO_REUSEADDR,&opt,sizeof(opt));
perror("setsockopt");
//server sockaddr_in
server.sin_family = AF_INET;
server.sin_port = htons(10000);
server.sin_addr.s_addr = htonl(INADDR_ANY);
if(bind(listen_fd,(struct sockaddr *)&server,sizeof(server)) < 0)
{
perror("bind");
return -1;
}
if(listen(listen_fd,10) < 0)
{
perror("listen");
return -1;
}
socklen_t len;
pthread_t pid;
struct Arg *arg;
while(1)
{
len = sizeof(client1);
conn_fd = accept(listen_fd,(struct sockaddr *)&client1,&len);
if(conn_fd < 0)
{
perror("accetp");
continue;
}
arg = (struct Arg *)malloc(sizeof(struct Arg));
arg->fd = conn_fd;
//arg->client = client1;
memcpy((void *)&arg->client,&client1,sizeof(client1));
perror("memcpy");
if(pthread_create(&pid,NULL,function,(void *)arg) != 0)
{
perror("pthread_create");
close(conn_fd);
free(arg);
exit(-1);;
}
}
close(conn_fd);
return 0;
}
void *function(void *arg)
{
char recv_buf[127+1];
struct Arg *para;
para = (struct Arg *)arg;
printf("yOU GET LINK FROM :%s\n",inet_ntoa(para->client.sin_addr));
memset(recv_buf,0,sizeof(recv_buf));
strcpy(recv_buf,"welcome");
send(para->fd,recv_buf,strlen(recv_buf),0);
free(arg);
}
gcc指令:gcc -lpthread threadserver -o threadserve.c