Advertisement
heavenriver

socketC.c

Nov 27th, 2013
49
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 2.09 KB | None | 0 0
  1. /* basic socket operations, UNIX-native */
  2.  
  3.  /* pointer arithmetics:
  4.   *
  5.   * push(pointer, v) INDICATES *(pointer++) = v
  6.   * pop(pointer) INDICATES *(--pointer)
  7.   * (*++v)[0] INDICATES (**++v)
  8.   *           INDICATES first char in v
  9.   *           INDICATES name of string/vector v
  10.   * likewise, *v[0] INDICATES **v
  11.   *       and *v[n] INDICATES **(v + n)
  12.   * returntype (*funct)(args) INDICATES a function funct with arguments args which returns...
  13.   * char **argv INDICATES pointer to char pointer
  14.   * int(*v)[len] INDICATES pointer "v" to a vector of "len" int elements
  15.   * int *v[len] INDICATES vector "v" of "len" pointers to int elements
  16.   * void *funct() INDICATES function "funct" that returns a pointer-to-void
  17.   * void (*funct)() INDICATES pointer to a function "funct" that returns void
  18.   *
  19.   */
  20.  
  21.  /* useful characters: [] # */
  22.  
  23.  # include <stdio.h>
  24.  # include <stdlib.h> // for exit
  25.  # include <sys/types.h>
  26.  # include <sys/socket.h>
  27.  # include <netinet/in.h>
  28.  # include <netdb.h>
  29.  
  30.  # define SIZE 1024
  31.  # define exception(x) { puts(x); exit(1); }
  32.  
  33.  int main(int argc, char * argv[])
  34.     {
  35.      /* recvfrom */
  36.      int sock;
  37.      struct sockaddr_in mysock;
  38.      struct sockaddr addr;
  39.      int addrlen;
  40.      char buffer[SIZE]; // stores data
  41.      sock = socket(AF_INET, SOCK_DGRAM, 0); // UDP socket
  42.      mysock.sin_family = AF_INET;
  43.      mysock.sin_port = 1999;
  44.      mysock.sin_addr.s_addr = INADDR_ANY;
  45.      bind(sock, &mysock, sizeof(mysock)); // binding sock and mysock
  46.      // COMMENTED LINE BELOW causes infinite loop, why?
  47.      //if(recvfrom(sock, buffer, SIZE, 0, &addr, &addrlen) == -1) // done receiving condition
  48.     exception("Call error in recvfrom(...)\n");
  49.      
  50.      
  51.      /* sendto */
  52.      /* SOCK, MYSOCK and BUFFER will be used without being reinstanced */
  53.      int success;
  54.      struct hostent * hp;
  55.      hp = gethostbyname("dis.uniroma1.it");
  56.      memcpy(&mysock.sin_addr, hp->h_addr, 4);
  57.      success = sendto(sock, buffer, SIZE, 0, &mysock, sizeof(mysock));
  58.      if(success == -1) exception("Call error in sendto(...)\n");
  59.      
  60.      return 0;
  61.     }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement