C语言socket通信实例
时间: 2023-07-08 19:27:05 浏览: 72
下面是一个简单的C语言socket通信实例,演示了如何使用socket在两个程序之间进行通信。
客户端代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
int main()
{
int sockfd, portno, n;
struct sockaddr_in serv_addr;
struct hostent *server;
char buffer[256];
portno = 8888;
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0)
{
perror("Error opening socket");
exit(1);
}
server = gethostbyname("127.0.0.1");
if (server == NULL)
{
fprintf(stderr,"Error, no such host\n");
exit(1);
}
bzero((char *) &serv_addr, sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
bcopy((char *)server->h_addr, (char *)&serv_addr.sin_addr.s_addr, server->h_length);
serv_addr.sin_port = htons(portno);
if (connect(sockfd, (struct sockaddr *) &serv_addr, sizeof(serv_addr)) < 0)
{
perror("Error connecting");
exit(1);
}
printf("Please enter the message: ");
bzero(buffer,256);
fgets(buffer,255,stdin);
n = write(sockfd, buffer, strlen(buffer));
if (n < 0)
{
perror("Error writing to socket");
exit(1);
}
bzero(buffer,256);
n = read(sockfd, buffer, 255);
if (n < 0)
{
perror("Error reading from socket");
exit(1);
}
printf("%s\n",buffer);
close(sockfd);
return 0;
}
```
服务器端代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
int main()
{
int sockfd, newsockfd, portno, clilen;
char buffer[256];
struct sockaddr_in serv_addr, cli_addr;
int n;
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0)
{
perror("Error opening socket");
exit(1);
}
bzero((char *) &serv_addr, sizeof(serv_addr));
portno = 8888;
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = INADDR_ANY;
serv_addr.sin_port = htons(portno);
if (bind(sockfd, (struct sockaddr *) &serv_addr, sizeof(serv_addr)) < 0)
{
perror("Error on binding");
exit(1);
}
listen(sockfd,5);
clilen = sizeof(cli_addr);
newsockfd = accept(sockfd, (struct sockaddr *) &cli_addr, &clilen);
if (newsockfd < 0)
{
perror("Error on accept");
exit(1);
}
bzero(buffer,256);
n = read(newsockfd, buffer, 255);
if (n < 0)
{
perror("Error reading from socket");
exit(1);
}
printf("Here is the message: %s\n", buffer);
n = write(newsockfd,"I got your message",18);
if (n < 0)
{
perror("Error writing to socket");
exit(1);
}
close(newsockfd);
close(sockfd);
return 0;
}
```
在这个例子中,客户端连接到服务器,并发送一条消息。服务器接收该消息并发送一条回复。客户端接收回复后关闭socket连接。
阅读全文