------------------------------------------------------------------
# vi receive_socket.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>
#define SERV_TCP_PORT 9090
#define SERV_ADDR "127.0.0.1"
int 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,50);
buf[10]=0;
printf("what echoed from the server is %s\n",buf);
}
-----------------------------------------------------------------
# vi send_socket.c
-------------------------------------------------------------------
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#define SERV_TCP_PORT 9090
#define SERV_ADDR "127.0.0.1"
int main()
{
int s1,s2,x;
struct sockaddr_in serv_addr;
struct sockaddr_in cli_addr;
char buf[20];
int 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);
}
--------------------------------------------------------------
compile 하기
------------------------------------------------------------
# gcc -o receive receive_socket.c
# gcc -o send send_socket.c
---------------------------------------------------------
< 실행 방법 >
# ./receive
대기하고 있음
# ./send
#