Interview Questions

Code Sample: How to disposing of a Socket ?

Beginners Guide to Sockets


(Continued from previous question...)

Code Sample: How to disposing of a Socket ?

Code Sample: How to disposing of a Socket

#include &ltstdio.h>

void close(int s).

/* The I/O call close() will close the socket
descriptor s just as it closes
any open file descriptor.
Example - sendto() and recvfrom()
*/



/* receiver */
#include &ltsys/types.h>
#include &ltsys/socket.h>

struct sockaddr myname;
struct sockaddr from_name;
char buf[80];

main()
{
  int   sock;
  int   fromlen, cnt;

  sock = socket(AF_UNIX, SOCK_DGRAM, 0);
  if (sock < 0) {
    printf("socket failure %d\n", errno);
    exit(1);
  }

  myname.sa_family = AF_UNIX;
  strcpy(myname.sa_data, "/tmp/tsck");

if (bind(sock, &myname,
 strlen(myname.sa_data) +
        sizeof(name.sa_family)) < 0) {
    printf("bind failure %d\n", errno);
    exit(1);
  }

  cnt = recvfrom(sock, buf, sizeof(buf),
    0, &from_name, &fromlen);
  if (cnt < 0) {
    printf("recvfrom failure %d\n", errno);
    exit(1);
  }

  buf[cnt] = '\0';  /* assure null byte */
  from_name.sa_data[fromlen] = '\0';

  printf("'%s' received from %s\n",
    buf, from_name.sa_data);
}

/* sender */
#include &ltsys/types.h>

#include &ltsys/socket.h>

char buf[80];
struct sockaddr to_name;

main()
{
  int   sock;

  sock = socket(AF_UNIX, SOCK_DGRAM, 0);
  if (sock < 0) {
    printf("socket failure %d\n", errno);
    exit(1);
  }

  to_name.sa_family = AF_UNIX;
  strcpy(to_name.sa_data, "/tmp/tsck");

  strcpy(buf, "test data line");

 cnt = sendto(sock, buf, strlen(buf),
  0, &to_name,
    strlen(to_name.sa_data) + 
    sizeof(to_name.sa_family));
  if (cnt < 0) {
    printf("sendto failure %d\n", errno);
    exit(1);
  }
}

(Continued on next question...)

Other Interview Questions