A forum for questions and answers about network programming on Linux and all other Unix-like systems

You are not logged in.

#1 2007-03-08 05:53 PM


Re: UDP echo server


I am trying to write a simple UDP echo server in C.
The server should listen on a specific port and every incoming udp package has to be redirected to another IP-address on the same port. My first try was to write a TCP echo server that simply echos all incoming data on port 6666 using a while loop:

while( (bytesrecv = recv(socketid, buffer, sizeof(buffer), 0)) > 0)
        send(socketid, buffer, bytesrecv, 0);

and it worked. But I think I am to stupid to manage this with an udp socket.
Instead of recv() and send() I use recvfrom() and sendto() with this sockaddr_in struct as parameter. recvfrom() works fine but the sendto() function always returns -1 (Invalid parameter). I think it has something to to with the sockaddr_in struct.

I'd like to post a part of my code but at the moment I cannot access the server my soucecode is on.

Can someone provide me a very simple example?

Thank you very much!!!!!


#2 2007-03-08 08:06 PM

From: Boston, MA
Registered: 2002-06-12
Posts: 3,844

Re: UDP echo server

See the links from this post from me this morning...

Both the old FAQ sample code and UNP sample code contain simple UDP servers
of various sorts...  (I think only the UNP source has an actual UDP echo server,
though...)  Here's the main guts of the UDP echo server from UNP:

dg_echo(int sockfd, SA *pcliaddr, socklen_t clilen)
    int         n;
    socklen_t   len;
    char        mesg[MAXLINE];

    for ( ; ; ) {
        len = clilen;
        n = Recvfrom(sockfd, mesg, MAXLINE, 0, pcliaddr, &len);

        Sendto(sockfd, mesg, n, 0, pcliaddr, len);


Board footer

Powered by FluxBB