第一次编程
版权声明:原创作品,谢绝转载!否则将追究法律责任。 |
今天第一次编写了一个建立连接的程序,虽然还不是很懂,是照着书上面copy的,但是调通了也很happy,哈哈。
客户端的源文件:
#include<stdio.h>
#include<stdlib.h> #include<errno.h> #include<string.h> #include<netdb.h>
#include<sys/types.h> #include<netinet/in.h> #include<sys/socket.h> int main (int argc,char * * argv)
{ int sockfd,numb; struct sockaddr_in s; struct hostent *host; char buf [100]; int port = 8000; if(argc!=2){
fprintf(stderr,"usage: %s hostname \n",argv [0]); exit (1); } if(!(host=gethostbyname (argv[1]))) { perror ("error in resolving hostname"); exit (1); } sockfd = socket (AF_INET,SOCK_STREAM,0); if (sockfd<0){ perror("socket"); exit(1); } bzero(&s, sizeof(s)); s.sin_family=AF_INET; s.sin_addr.s_addr=((struct in_addr *)(host -> h_addr)) ->s_addr; s.sin_port=htons(port); if ((connect(sockfd,(struct sockaddr *) &s,sizeof(s)))!=0){ perror ("connect"); exit(1); } printf ("get connected! \n"); getchar(); strcpy(buf,"Give me the first file of the president's office"); if(send (sockfd,buf,strlen(buf),0)<0){ perror("send"); exit(1); } numb=recv(sockfd,buf,100,0); if(numb<0) { perror("recv"); exit(1); } buf [numb] ='\0'; printf("Received= %s \n",buf); close(sockfd); return 0; }
服务器端的源文件: #include<sys/param.h>
#include<stdio.h> #include<stdlib.h> #include<errno.h> #include<string.h> #include<sys/types.h> #include<netinet/in.h> #include<sys/socket.h> #include<arpa/inet.h> #include<netdb.h> int port = 8000;
void init_daemon(void) { pid_t pid; int i; if((pid = fork ()) == -1) exit(1); if (pid > 0) exit(0); setsid(); for(i=0;i<NOFILE;i++) close(i); chdir("/rundir"); umask(0); return; } int main (int ac ,char * * av)
{ int sockfd,tsockfd; int addr_size; char buf[100]; struct sockaddr_in s; struct sockaddr_in p; char temp_buf[256]; init_daemon();
sockfd=socket (AF_INET,SOCK_STREAM,0); if (sockfd == -1){ perror("socker building failure"); exit (1); } bzero(&s ,sizeof(s)); s.sin_family = AF_INET; s.sin_addr.s_addr = INADDR_ANY; s.sin_port = htons(port); bzero(&p,sizeof(p));
p.sin_family =AF_INET; p.sin_addr.s_addr = INADDR_ANY; p.sin_port = htons(port); addr_size = sizeof(p); if(bind(sockfd,(struct sockaddr *) &s ,sizeof (s))== -1){ perror("bind"); exit(1); } if (listen(sockfd,10) ==-1){
perror("listen"); exit(1); } for(;;){ tsockfd =accept (sockfd,(struct sockaddr *) &p, &addr_size); if ( tsockfd<0 ){ printf("ft:%d\n",errno); perror("accept"); exit(1); } if(recv (tsockfd,buf,100,0) < 0){ perror("recv"); exit(1); } strcpy (temp_buf,"Here is the first file of the president's office."); if (send(tsockfd,temp_buf,strlen(temp_buf),0<0)){ perror("send"); exit(1); } close(tsockfd); printf ("send:%s",temp_buf); } } 本文出自 “旱鸭子” 博客,谢绝转载! 本文出自 51CTO.COM技术博客 |


shiwbl
博客统计信息
热门文章
最新评论
友情链接
