nettcpserver.c
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/socket.h>
int main()
{
int sockfd,client_fd;
struct sockaddr_in my_addr;
struct sockaddr_in remote_addr;
int val=1;
if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1)
{
perror("socket");
exit(1);
}
setsockopt( sockfd, SOL_SOCKET, SO_REUSEADDR, (char*)&val, sizeof(val) );
my_addr.sin_family=AF_INET;
my_addr.sin_port=htons(3333);
my_addr.sin_addr.s_addr=inet_addr("127.0.0.1");
bzero(&(my_addr.sin_zero),8);
if (bind(sockfd, (struct sockaddr *)&my_addr, sizeof(struct sockaddr))== -1)
{
perror("bind");
exit(1);
}
if (listen(sockfd, 10) == -1)
{
perror("listen");
exit(1);
}
int sin_size = sizeof(struct sockaddr_in);
if ((client_fd = accept(sockfd, (struct sockaddr *)&remote_addr,&sin_size)) == -1)
{
perror("accept");
exit(1);
}
printf("received a connection from %s\n", inet_ntoa(remote_addr.sin_addr));
if (send(client_fd, "Hello, you are connected!\n", 26, 0) == -1)
{
perror("send");
close(client_fd);
exit(2);
}
close(client_fd);
close(sockfd);
return 0;
}
nettcpclient.c
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/socket.h>
int main(int argc, char *argv[])
{
int sockfd, recvbytes;
char buf[100];
struct hostent *host;
struct sockaddr_in serv_addr;
if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1)
{
perror("socket");
exit(1);
}
serv_addr.sin_family=AF_INET;
serv_addr.sin_port=htons(3333);
serv_addr.sin_addr.s_addr=inet_addr("127.0.0.1");
bzero(&(serv_addr.sin_zero),8);
if (connect(sockfd, (struct sockaddr *)&serv_addr,sizeof(struct sockaddr)) == -1)
{
perror("connect");
exit(1);
}
if ((recvbytes=recv(sockfd, buf, 100, 0)) ==-1)
{
perror("recv");
exit(1);
}
buf[recvbytes] = '\0';
printf("Received: %s",buf);
close(sockfd);
return 0;
}
最新评论