Network/_Network Programming
리눅스 소켓 예제소스
Dakuo
2010. 3. 30. 14:27
Server.c #include <stdio.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #define SERV_TCP_PORT 1111 // 개방할 포트 #define SERV_ADDR "111.111.111.111" // 서버 IP main() { int s1,s2,x; struct sockaddr_in serv_addr, cli_addr; char buf[20]; size_t xx; printf("Hi, I am the server\n"); bzero((char *)&serv_addr, sizeof(serv_addr)); serv_addr.sin_family=AF_INET; serv_addr.sin_addr.s_addr=inet_addr(SERV_ADDR); serv_addr.sin_port=htons(SERV_TCP_PORT); if((s1=socket(PF_INET, SOCK_STREAM, 0))<0) { printf("socket creation error\n"); exit(1); } printf("socket created successfully. socket num is %d\n", s1); x=bind(s1, (struct sockaddr *)&serv_addr, sizeof(serv_addr)); if (x < 0) { printf("binding failed\n"); exit(1); } printf("binding passed\n"); listen(s1, 5); xx = sizeof(cli_addr); s2 = accept(s1,(struct sockaddr *)&cli_addr,&xx); printf("we passed accept. new socket num is %d\n", s2); read(s2,buf,10); buf[10]=0; printf("we got %s from cli\n",buf); printf("what do you want to send to cli? enter your string\n"); scanf("%s", buf); write(s2,buf,strlen(buf)); exit(0); }
Client.c #include <stdio.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #define SERV_TCP_PORT 1111 // 연결할 포트 #define SERV_ADDR "111.111.111.111" // 접속할 서버의 IP main() { int x; struct sockaddr_in serv_addr; char buf[50]; printf("Hi, I am the client\n"); bzero((char *) &serv_addr, sizeof(serv_addr)); serv_addr.sin_family = PF_INET; serv_addr.sin_addr.s_addr = inet_addr(SERV_ADDR); serv_addr.sin_port = htons(SERV_TCP_PORT); /* open a tcp socket*/ if ( (x =socket(PF_INET, SOCK_STREAM,0)) < 0) { printf("socket creation error\n"); exit(1); } printf(" socket opened successfully. socket num is %d\n", x); /* connect to the server */ if (connect(x, (struct sockaddr *) &serv_addr, sizeof(serv_addr))<0) { printf("can't connect to the server\n"); exit(1); } /* send input str to the server */ printf("now i am connected to the erver. enter a string to send\n"); scanf("%s", buf); write(x,buf,strlen(buf)); printf("now let's read from the server\n"); read(x,buf,10); buf[10]=0; printf("what echoed from the server is %s\n",buf); }