티스토리 뷰

Web & Network

UDPEchoServer

pwnbit 2013. 10. 30. 09:51
반응형

#include <stdio.h>

#include <sys/socket.h>

#include <arpa/inet.h>

#include <stdlib.h>

#include <string.h>

#include <unistd.h>


#define ECHOMAX 255


void DieWithError(char *errorMessage);


int main(int argc, char *argv[])

{

int sock;

struct sockaddr_in echoServAddr;

struct sockaddr_in echoClntAddr;

unsigned int cliAddrLen;

char echoBuffer[ECHOMAX];

unsigned short echoServPort;

int recvMsgSize;


if (argc != 2)

{

fprintf(stderr,"Usage: %s <UDP SERVER PORT> \n", argv[0]);

exit(1);

}

echoServPort = atoi(argv[1]);


if ((sock = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP)) < 0)

DieWithError("socket() failed");


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

echoServAddr.sin_family = AF_INET;

echoServAddr.sin_addr.s_addr = htonl(INADDR_ANY);

echoServAddr.sin_port = htons(echoServPort);


if (bind(sock, (struct sockaddr *) &echoServAddr, sizeof(echoServAddr)) < 0)

DieWithError("bind() failed");

for (;;)

{


cliAddrLen = sizeof(echoClntAddr);


if ((recvMsgSize = recvfrom(sock, echoBuffer, ECHOMAX, 0,

(struct sockaddr *) &echoClntAddr, &cliAddrLen)) < 0)

DieWithError("recvfrom() failed");

printf("Handling client %s \n", inet_ntoa(echoClntAddr.sin_addr));


if (sendto(sock, echoBuffer, recvMsgSize, 0,

(struct sockaddr *) &echoClntAddr, sizeof(echoClntAddr)) != recvMsgSize)

DieWithError("sendto() sent a different number of bytes than expected");

}

}







반응형

'Web & Network' 카테고리의 다른 글

자바스크립트 자동 새로고침  (0) 2015.09.29
멀티태스킹(Multi tasking)  (0) 2013.11.11
신호(Signals)  (0) 2013.11.04
UDPEchoServer  (0) 2013.10.30
소켓옵션들  (0) 2013.10.28
tcp/ip 소켓 프로그래밍 함수 소개  (0) 2013.09.16
TAG
댓글
댓글쓰기 폼
반응형
공지사항
Total
226,157
Today
6
Yesterday
30
링크
«   2021/09   »
      1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30    
글 보관함