server side
#include <unistd.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/types.h>
#include <sys/socket.h>
int sfd, rsfd;
struct sockaddr saddr; // listener
struct sockaddr rsaddr;
sfd = socket(AF_INET, SOCK_STREAM, IPPROTO_IP);
saddr.sin_family = AF_INET;
saddr.sin_port = 10000;
saddr.sin_addr.s_addr = inet_addr("100.100.100.100");
// or inet_aton
bind(sfd, (struct sockaddr*)&saddr, sizeof(saddr));
listen(sfd, BACKLOG);
rsfd = accept(sfd, (struct sockaddr *)&saddr, &len_rsaddr);
recv(rsfd, rbuf, sizeof(rbuf), 0);
send(rsfd, sbuf, sizeof(sbuf), 0);
shutdown(rsfd, SHUT_RDWR); // or close
client side
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/socket.h>
int sfd;
struct sockaddr saddr;
sfd = socket(AF_INET, SOCK_STREAM, IPPROTO_IP);
saddr.sin_family = AF_INET;
saddr.sin_port = 10000;
inet_aton("100.100.100.100", &saddr.sin_addr);
// or inet_addr
connect(sfd, (struct sockaddr*)saddr, sizeof(saddr));
send(sfd, sbuf, sizeof(sbuf), 0);
recv(sfd, rbuf, sizeof(rbuf), 0);
close(sfd); // or shutdown
No comments:
Post a Comment