#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");

}

}







'Network' 카테고리의 다른 글

멀티태스킹(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

+ Recent posts

티스토리 툴바