内容发布更新时间 : 2024/12/28 22:34:13星期一 下面是文章的全部内容请认真阅读。
#include
#include
#define N 64
typedef struct sockaddr SA;
int main(int argc, char *argv[]) {
if(argc < 3) {
printf(\,argv[0]); exit(-1); }
int listenfd, connfd;
struct sockaddr_in myaddr, peeraddr; char buf[N] = {0}; size_t n;
socklen_t mylen, peerlen; mylen = sizeof(myaddr);
peerlen = sizeof(peeraddr); /* create socket */
if ((listenfd = (socket(PF_INET, SOCK_DGRAM, 0))) < 0) {
perror(\); exit(-1); }
/* bind initialization */ bzero(&myaddr, mylen);
myaddr.sin_family = PF_INET;
myaddr.sin_port = htons(atoi(argv[2])); inet_aton(argv[1], &myaddr.sin_addr);
if(bind(listenfd,(SA *)&myaddr, sizeof(myaddr)) < 0) {
perror(\); exit(-1); }
/* listen */ listen(listenfd, 5); /* accept */
if(-1 == (connfd = accept(listenfd, (SA *)&peeraddr, &peerlen))) {
perror(\); exit(-1); }
printf(\,inet_ntoa(peeraddr.sin_addr), ntohs(peeraddr.sin_port)); /* recv-send */ while(1){
n = recv(connfd, buf, N, 0); buf[n] = 0;
printf(\,n,buf); if(0 == strncmp(buf,\,4)) break;
send(connfd, buf, strlen(buf), 0); }
close(connfd); close(listenfd); exit(0); }
资料博客源地址:
http://www.cnblogs.com/lr-ting/archive/2012/08/24/2652482.html