How to disposing of a Socket?

Answer

Code Sample: How to disposing of a Socket

#include <stdio.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 <sys/types.h>
#include <sys/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 %dn", 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 %dn", errno);
exit(1);
}

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

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

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

/* sender */
#include <sys/types.h>

#include <sys/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 %dn", 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 %dn", errno);
exit(1);
}

All sockets Questions

Ask your interview questions on sockets

Write Your comment or Questions if you want the answers on sockets from sockets Experts
Name* :
Email Id* :
Mob no* :
Question
Or
Comment* :
 





Disclimer: PCDS.CO.IN not responsible for any content, information, data or any feature of website. If you are using this website then its your own responsibility to understand the content of the website

--------- Tutorials ---