Thursday, October 02, 2008

Socket programming with C

Requirements:
  • Compile two .c files;
  • Run compiled files in 2 windows
  • Analyze the result.

#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 

#define PORT 1234

char localhost[] = "localhost";

int main(int argc, char *argv[])
{
 struct hostent *ptrh;
    struct sockaddr_in their_addr;
    int    sd;
    char   *host;
    int    n = 0;
    char   c;     
    
    if (argc > 1)
  host = argv[1];
    else
  host = localhost;
    
    if ((ptrh = gethostbyname(host)) == NULL) {
  fprintf(stderr,"Host: %s not found\n", host);
  exit(1);
    }

    
    if ((sd = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
  perror("socket:");
  exit(1);
    } 

    memset((char *)&their_addr, 0, sizeof(their_addr));
    their_addr.sin_family = AF_INET;
    their_addr.sin_port = htons(PORT);
    their_addr.sin_addr = *((struct in_addr *)ptrh->h_addr);
    
    if (connect(sd, (struct sockaddr *)&their_addr, sizeof(their_addr)) < 0) {
  fprintf(stdout,"Connecting to %s \n", \
  inet_ntoa(their_addr.sin_addr));
  perror("connect: ");
  exit(1);
    }
    
    n = 0;
    fprintf(stdout, "Type a new line: ");
    for (;;) {
  c = getchar();
  write(sd, &c, 1);
  if (c == '\n') break;
  n++;
 }
    
    for (;;) {
  read(sd, &c, 1);
  putchar(c);
  if (c == '\n') break;
    }
    
    close(sd);
     
    return 0;
}

#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 

#define MYPORT 1234
#define QLEN 6

void echo_upper(int sockfd)
{
    for ( ; ; ) {
  ssize_t n;
  char c;
   
  n = read(sockfd, &c, 1);
  if (n > 0) {
        c = toupper(c);
        write(sockfd, &c, 1);
        putchar(c);
  } else if ( n < 0) {
        fprintf(stderr, "Reading error\n");
        return;
  } else
        return;
    }
}

int main()
{
    struct sockaddr_in my_addr;
    int    sd;
    
    memset((char *)&my_addr, 0, sizeof(my_addr));
    my_addr.sin_family = AF_INET;
    my_addr.sin_addr.s_addr = INADDR_ANY;
    my_addr.sin_port = htons(MYPORT);
    
 if ((sd = socket(AF_INET, SOCK_STREAM, 0))== -1) {
  perror("socket:");
  exit(1);
    }

 if (bind(sd, (struct sockaddr *)&my_addr, sizeof(struct sockaddr)) == -1) {
  perror("bind:");
  exit(1);
    }
 
    if (listen(sd, QLEN) < 0) {
  fprintf(stderr, "listen failed\n");
  exit(1);
    }
     
    while (1) {
  struct sockaddr_in their_addr;
  int    alen;
  int    sd2;
   
  alen = sizeof(their_addr);
  if ((sd2 = accept(sd, (struct sockaddr *)&their_addr, &alen)) == -1){
   perror("accept:");
   continue;
  }
  fprintf(stdout, "Connected to %s \n", inet_ntoa(their_addr.sin_addr));
  echo_upper(sd2);
  close(sd2);
  fprintf(stdout, "\nConnection closed\n");
    }
}

No comments: