#include <stdio.h> #include <sys/types.h> #include <sys/socket.h> #include <string.h> #include <netinet/in.h> #include <arpa/inet.h> #include <stdlib.h> #include <pthread.h> static void usage (const char *PROC) { printf ("Usage:%s [IP] [port]\n", proc); } void *thread_run (void *arg) { printf ("Create a new thread\n"); int fd= (int) arg; Char buf[1024]; while (1) { memset (buf, ' n ', sizeof (BUF)); ssize_t _s=read (fd,buf,sizeof (BUF)-1); if (_s>0) { buf[_s]= ' + '; printf ("client#%s\n", buf); Write (Fd,buf,strlen (BUF)); }else if (_s==0) { printf ("Client close...\n"); Break }else{ printf ("Read error...\n"); Break } } return (void *) 0; } int main (int argc,char *argv[]) { if (argc!=3) { Usage (argv[0]); Exit (1); } 1. Creat sock int Listen_sock=socket (af_inet,sock_stream,0); if (listen_sock<0) { Perror ("socket"); return 1; } struct SOCKADDR_IN local; Local.sin_family=af_inet; Local.sin_port=htons (Atoi (argv[2)); //Port number LOCAL.SIN_ADDR.S_ADDR=INET_ADDR (argv[1]); //IP Address //2. Bind if (Bind (Listen_sock, (struct sockaddr*) &local,sizeof (local)) <0) { Perror ("bind"); return 2; } //3. Listen Listen (listen_sock,5); //4. Accept struct SOCKADDR_IN peer; Socklen_t len=sizeof (peer); while (1) { int Fd=accept (Listen_sock, (struct sockaddr*) &peer,&len); if (fd<0) { Perror ("accept"); return 3; } printf ("Get a new Link,socket-%s:&d\n", Inet_ntoa (PEER.SIN_ADDR), Ntohs (Peer.sin_port)); pthread_t ID; Pthread_create (&id,null,thread_run, (void*) FD); Pthread_detach (ID); } return 0; } |