UDP 기반 에코 서버/클라이언트
2448 단어 TCP/IP 네트워크 프로그래밍
#include
#include
#include
#include
#include
#include
#define MAXN 1024
void error_handling(const char *str)
{
fputs(str,stderr);
fputc('
',stderr);
exit(1);
}
int main(int argc,char *argv[])
{
int serv_sock;
int n=5,str_len;
struct sockaddr_in serv_addr;
struct sockaddr_in clnt_addr;
socklen_t clnt_addr_size;
char msg[MAXN];
if(argc!=2)
{
printf("Usage:%s
",argv[0]);
exit(1);
}
serv_sock=socket(PF_INET,SOCK_DGRAM,0); // : SOCK_DGRAM
if(serv_sock==-1)
error_handling("socket() error");
memset(&serv_addr,0,sizeof(serv_addr));
serv_addr.sin_family=AF_INET;
serv_addr.sin_addr.s_addr=htonl(INADDR_ANY);
serv_addr.sin_port=htons(atoi(argv[1]));
if(bind(serv_sock,(struct sockaddr*)&serv_addr,sizeof(serv_addr))==-1) //
error_handling("bind() error");
while(n--)
{
clnt_addr_size=sizeof(clnt_addr);
str_len=recvfrom(serv_sock,msg,MAXN,0,(struct sockaddr*)&clnt_addr,&clnt_addr_size); //
sendto(serv_sock,msg,str_len,0,(struct sockaddr*)&clnt_addr,clnt_addr_size); //
}
close(serv_sock);
return 0;
}
//클라이언트 코드:
#include
#include
#include
#include
#include
#include
#define MAXN 1024
void error_handling(const char *str)
{
fputs(str,stderr);
fputc('
',stderr);
exit(1);
}
int main(int argc,char *argv[])
{
int clnt_sock,str_len;
struct sockaddr_in serv_adr,from_adr;
socklen_t from_adr_sz;
char msg[]="HelloWorld";
char store[1024];
if(argc!=3)
{
printf("ERROR
");
exit(1);
}
clnt_sock=socket(PF_INET,SOCK_DGRAM,0); //
if(clnt_sock==-1)
error_handling("socket() error");
memset(&serv_adr,0,sizeof(serv_adr));
serv_adr.sin_family=AF_INET;
serv_adr.sin_addr.s_addr=inet_addr(argv[1]);
serv_adr.sin_port=htons(atoi(argv[2]));
str_len=sendto(clnt_sock,msg,strlen(msg),0,(struct sockaddr*)&serv_adr,sizeof(serv_adr)); //
from_adr_sz=sizeof(from_adr);
recvfrom(clnt_sock,store,str_len,0,(struct sockaddr*)&from_adr,&from_adr_sz); //
store[str_len]='\0';
printf("Message from server: %s
",store);
close(clnt_sock);
return 0;
}