Docsity

Network Programming Primer-Network Programming-Lecture Slides, Slides of Network Programming

Partial preview of the text

Download Network Programming Primer-Network Programming-Lecture Slides and more Slides Network Programming in PDF only on Docsity!

Network Programming Primer

UDP

Writing a client server

Application

• Server waits for the client to connect

• Client connects

• Server sends back a string

• Client prints the string and exits

• Server again starts waiting for new connection

UDP based client contd.

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

int sockfd, numbytes;

char buf[MAXDATASIZE];

struct sockaddr_in their_addr;

// server’s address information

int errorVal;

UDP based client contd.

WSADATA wsaData;

if (WSAStartup(MAKEWORD(2, 2),&wsaData)!= 0)

fprintf(stderr, "WSAStartup failed.\n");

exit(1);

UDP based client contd.

if ((sockfd = socket(AF_INET, SOCK_DGRAM, 0)) == -1) { perror("socket"); WSACleanup( ); exit(1); }

UDP based client contd.

their_addr.sin_family = AF_INET; // host byte order their_addr.sin_port = htons(PORT); // short, network byte order

their_addr.sin_addr.s_addr = inet_addr(argv[1]); memset(&(their_addr.sin_zero), 0, 8); // zero the rest of the struct

UDP based client contd.

if ( (numbytes=sendto(sockfd, "Hello, world!\n", 14, 0, (struct sockaddr *)&their_addr, sizeof(struct sockaddr) ) ) == -1) { perror("send"); errorVal=WSAGetLastError(); }

UDP based client contd.

if ( (numbytes=recv(sockfd, buf, MAXDATASIZE-1, 0)) == -1) { perror("recv"); errorVal=WSAGetLastError(); }

UDP based server

#include <stdio.h>

#include <stdlib.h>

#include <string.h>

#include <winsock.h>

#define MYPORT 13490

// the port users will be connecting to

#define MAXDATASIZE 100

// max number of bytes we can get at once docsity.com

UDP based server contd

int main(void)

int sockfd;

struct sockaddr_in my_addr, their_addr;

char buf[MAXDATASIZE];

int numBytes, size, errorVal;

UDP based server contd

my_addr.sin_family = AF_INET; // host byte order my_addr.sin_port = htons(MYPORT); // short, network byte order my_addr.sin_addr.s_addr = INADDR_ANY; // automatically fill with my IP memset(&(my_addr.sin_zero), 0, 8); // zero the rest of the struct

UDP based server contd

if ( bind(sockfd, (struct sockaddr *)&my_addr, sizeof(struct sockaddr) ) == -1) { perror("bind"); WSACleanup( ); exit(1); }

UDP based server contd

if ( (numBytes=sendto(sockfd, buf, numBytes, 0, (struct sockaddr *)&their_addr, sizeof(struct sockaddr) ) ) == -1) { perror("send"); errorVal=WSAGetLastError(); } fprintf(stderr, "%d bytes sent to client\n",numBytes);

UDP based server contd

closesocket(new_fd); WSACleanup( ); return 0; } //main ends here