socket 통신 코드 연습--매일 조금씩 진보

 
 

/* */

#include <stdio.h>

#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

void die(char *msg)
{
perror(msg);
exit(1);
}


void copy_data(int from,int to)
{
char buf[1024];
int amount;
while((amount=read(from,buf,sizeof(buf)))>0) {
if(write(to,buf,amount) !=amount)
{
 die("write");
return;
}
}
if(amount <0) die("read");
}



int main()
{
int sock,conn,i;
struct sockaddr_in addr;
size_t addr_len =sizeof(addr);
if((sock = socket(PF_INET,SOCK_STREAM,0))<0)
die("socket");
 

i=1;
setsocketopt(sock,SOL_SOCKET,SO_REUAEADDR,&i,sizeof(i));
memset(&addr,0,sizeof(addr));
addr.sin_family = AF_INET;
addr.sin_addr.s_addr=htonl(INADDR_ANY);
addr.sin_port =htons(8888);


if(bind(sock,(struct sockaddr *)&addr,sizeof(addr))) 
die("blind");



if (lisetn(socket,5))
die("listen");



while((conn=accept(sock,(struct sockaddr *)&addr,&addr_len)) >=0){
printf("Accept %s:%d
",inet_ntoa(addr.sin_addr),addr.sin_port);
copy_data(conn,STDOUT_FILENO);
printf("Done!
");
close(conn);
}
return 0;

}

/* */

#include <stdil.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>




int main(int argc,const char *argv[])
{
struct sockaddr_in addr;
int sock;
if (argc !=2){
fprintf (stderr,"need an IP address
");
return -1;
}

memset(&addr,0,sizeof(addr));

addr.sin_family =AF_INET;
inet_aton(argv[1],&addr.sin_addr);
addr.sin_port =htons(8888);
if ((sock =socket(PF_INET,SOCK_STREAN,0)) <0{
die("socket");
}
if (connect(sock,(struct sockaddr *)&addr,sizeof(addr))){
die("connect");
}
printf("Connected!
);
copy_data(STDIN_FILENO,sock);
close(sock);
return 0;
}


좋은 웹페이지 즐겨찾기