Pulkit Gaur

dream - do - deserve

UDP Data Xchange

Filed under: C at 02:36:04 On 2006-07-11

Was working on a UDP dataXcahnge project ,thought this code fragment will be of some use to newbees.

 

Server Code :

 

#include <netinet/in.h>

#include <sys/socket.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

#include <arpa/inet.h>
#include <sys/types.h>


#define BUFLEN 512
#define PORT 10000

void die_err(char *s)
{
    perror(s);
    exit(1);
}

int main(void)
{
    struct sockaddr_in *sock_server, *sock_client;
    int s;
    socklen_t socklen=sizeof(struct sockaddr_in);
    char buf[BUFLEN];

    sock_server = malloc( socklen );
    sock_client = malloc( socklen );
    if ( !sock_server || !sock_client )
        die_err( "allocation failed" );
    if ((s=socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP))==-1)
        die_err("socket");
    sock_server->sin_family = AF_INET;
    sock_server->sin_port = htons(PORT);
    sock_server->sin_addr.s_addr = htonl(INADDR_ANY);
    if ( bind(s, (struct sockaddr *)sock_server, socklen )==-1)
        die_err("bind");

    while( 1 ) {
        if (recvfrom(s, buf, BUFLEN, 0,
                     (struct sockaddr *)sock_client, &socklen)==-1)
            die_err("recvfrom()");
        printf("Received packet from %s:%d\nData: %s\n",
               inet_ntoa(sock_client->sin_addr),
               ntohs(sock_client->sin_port), buf);
    }

    close(s);
    return 0;
}

 

 

 Client Code :

 

#include <netinet/in.h>

#include <sys/socket.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

#include <arpa/inet.h>
#include <sys/types.h>



#define BUFLEN 512
#define PORT 10000
#define USERVER "127.0.0.1"

void die_err(char *s)
{
    perror(s);
    exit(1);
}

int main(void)
{
    struct sockaddr_in *sock_server;
    int s, i;
    socklen_t socklen=sizeof(struct sockaddr_in);
    char buf[BUFLEN];

    sock_server = malloc( socklen );
    if ( !sock_server )
        die_err( "allocation failed" );
    if ((s=socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP))==-1)
        die_err("socket");
    sock_server->sin_family = AF_INET;
    sock_server->sin_port = htons(PORT);
    if (inet_aton(USERVER, &(sock_server->sin_addr))==0) {
        fprintf(stderr, "inet_aton() failed\n");
        exit(1);
    }

    for (i=0; i<3; i++) {
        printf("Sending packet %d\n", i);
        sprintf(buf, "This is packet %d\n", i);
        if (sendto(s, buf, BUFLEN, 0,
                   (struct sockaddr*)sock_server, socklen)==-1)
            die_err("sendto()");
    }

    close(s);
    return 0;
}

Leave a Comment

Required

Required, hidden