重复造轮子-linux-socket
#include <stdio.h> #include <sys/socket.h> #include <sys/types.h> #include <netinet/in.h> #include <unistd.h> #include <stdlib.h> #include <time.h> #include <arpa/inet.h> #define BUFFER_SIZE 255 #define SERVER_PORT 13579 #define LIGEN_OF_LISTEN_QUEUE 5 int main(int args, char** argv) { //init socket int servfd,clifd; struct sockaddr_in server_addr,client_addr; if((servfd = socket(AF_INET,SOCK_STREAM,0)) < 0) { printf("socket create error!\n"); exit(1); } server_addr.sin_family = AF_INET; server_addr.sin_port = htons(SERVER_PORT); server_addr.sin_addr.s_addr = htons(INADDR_ANY); if(bind(servfd,(struct sockaddr*)&server_addr,sizeof(server_addr)) < 0) { printf("bind to port %d\n failure!", SERVER_PORT); exit(1); } if(listen(servfd, LIGEN_OF_LISTEN_QUEUE) < 0) { printf("create listen failure!\n"); exit(1); } while(1) { char buf[BUFFER_SIZE]; long timestamp; socklen_t length = sizeof(client_addr); clifd = accept(servfd,(struct sockaddr*)&client_addr,&length); if(clifd < 0) { printf("accept error !\n"); break; } //close and print message printf("from client IP:%s,Port:%d\n", inet_ntoa(client_addr.sin_addr),ntohs(client_addr.sin_port)); timestamp = time(NULL); //strcpy(buf,"hello! i am shaoyongyang!"); send(clifd,"hello world",BUFFER_SIZE,0); close(clifd); } printf("hello world\n"); }
编译环境
shaoyongyang@ubuntu:~/Public/xtranfer$ gcc --version gcc (Ubuntu/Linaro 4.6.3-1ubuntu5) 4.6.3 Copyright (C) 2011 Free Software Foundation, Inc. This is free software; see the source for copying conditions. There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。