56 lines
1.4 KiB
C
56 lines
1.4 KiB
C
#include <stdio.h>
|
|
#include <stdlib.h>
|
|
#include <string.h>
|
|
#include <sys/types.h>
|
|
#include <sys/socket.h>
|
|
#include <netinet/in.h>
|
|
#include <arpa/inet.h>
|
|
#include <fcntl.h>
|
|
#include <unistd.h>
|
|
#include <netinet/tcp.h>
|
|
#include <netdb.h>
|
|
#include <errno.h>
|
|
|
|
int main(int argc, const char * argv[]) {
|
|
char quit='q';
|
|
int server_sockfd;
|
|
int client_sockfd;
|
|
int len;
|
|
struct sockaddr_in my_add;
|
|
struct sockaddr_in remote_addr;
|
|
socklen_t sin_size;
|
|
char buf[BUFSIZ];
|
|
memset(&my_add,0,sizeof(my_add));
|
|
my_add.sin_family = AF_INET;
|
|
my_add.sin_addr.s_addr = INADDR_ANY;
|
|
my_add.sin_port = htons(8000);
|
|
|
|
server_sockfd=socket(PF_INET, SOCK_STREAM, 0);
|
|
|
|
bind(server_sockfd, (struct sockaddr *)&my_add, sizeof(struct sockaddr));
|
|
|
|
listen(server_sockfd, 5);
|
|
sin_size = sizeof(struct sockaddr_in);
|
|
|
|
client_sockfd=accept(server_sockfd, (struct sockaddr *)&remote_addr, &sin_size);
|
|
|
|
printf("accept client %s\n",inet_ntoa(remote_addr.sin_addr));
|
|
len = send(client_sockfd, "welcome to my server\n", 21, 0);
|
|
|
|
while (1) {
|
|
memset(buf,0,sizeof(buf));
|
|
len = recv(client_sockfd, buf, BUFSIZ, 0);
|
|
send(client_sockfd,buf, len, 0);
|
|
buf[len]='\0';
|
|
printf("receive:%s\n",buf);
|
|
if(buf[0]=='q'){
|
|
send(client_sockfd,&quit, 1, 0);
|
|
break;
|
|
}
|
|
}
|
|
close(client_sockfd);
|
|
close(server_sockfd);
|
|
return 0;
|
|
}
|
|
|