最简单的c代码tcp 发送接受程序
/* server.c
* 创建一个socket
* 绑定上自己的地址
* 然后就开始侦听客户端连接了.
* 有客户接入, 首先accept, 得到一个新的fd,
* 在这个新的fd上进行发送和接受
*/
/* tcp_send.c
* 创建一个socket
* 构建服务器地址 serv_addr
* 然后通过socket与服务器建立连接connect
* 然后就可以收发数据了. send,recv
* 需要在结束时关闭socket (close)
*/
具体代码如下: server.c
#include <netinet/in.h> // for sockaddr_in, htons, INADDR_ANY, in_addr
#include <stdio.h> // for perror, printf
#include <string.h> // for memset, strcpy, strlen
#include <sys/socket.h> // for accept, bind, listen, recv, send, socket
#include <unistd.h> // for close
/* server.c
* 创建一个socket
* 绑定上自己的地址
* 然后就开始侦听客户端连接了.
* 有客户接入, 首先accept, 得到一个新的fd,
* 在这个新的fd上进行发送和接受
*/
int main() {
int sockfd = socket(AF_INET, SOCK_STREAM, 0);
struct sockaddr_in serv_addr;
memset(&serv_addr, 0, sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = INADDR_ANY;
serv_addr.sin_port = htons(1234);
bind(sockfd, (struct sockaddr *) &serv_addr, sizeof(serv_addr));
listen(sockfd, 5);
char buffer[1024];
while (1) {
struct sockaddr_in client_addr;
socklen_t client_len = sizeof(client_addr);
int connfd = accept(sockfd, (struct sockaddr *) &client_addr, &client_len);
if (connfd < 0) {
perror("accept");
continue;
}
int n = recv(connfd, buffer, 1024, 0);
if (n == -1) {
perror("recv");
continue;
}
printf("Received: %s\n", buffer);
strcpy(buffer, "Hello, client!");
n = send(connfd, buffer, strlen(buffer), 0);
if (n == -1) {
perror("send");
continue;
}
close(connfd);
}
close(sockfd);
return 0;
}
tcp 客户端代码. tcp_send.c
#include <arpa/inet.h> // for inet_pton
#include <netinet/in.h> // for sockaddr_in, htons
#include <stdio.h> // for perror, fprintf, printf, stderr
#include <stdlib.h> // for exit
#include <string.h> // for strcpy, strlen
#include <strings.h> // for bzero
#include <sys/socket.h> // for AF_INET, connect, recv, send, socket, SOCK_S...
#include <unistd.h> // for close
/* tcp_send.c
* 创建一个socket
* 构建服务器地址 serv_addr
* 然后通过socket与服务器建立连接connect
* 然后就可以收发数据了. send,recv
* 需要在结束时关闭socket (close)
*/
int main(int argc, char *argv[]) {
if (argc != 2) {
fprintf(stderr, "Usage: %s <hostname>\n", argv[0]);
exit(1);
}
int sockfd = socket(AF_INET, SOCK_STREAM, 0);
//建立服务器地址
struct sockaddr_in serv_addr;
bzero((char *) &serv_addr, sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons(1234); //向1234端口发送
if (inet_pton(AF_INET, argv[1], &serv_addr.sin_addr) <= 0) {
fprintf(stderr, "Invalid address\n");
exit(1);
}
//与服务器建立连接,3次握手
if (connect(sockfd, (struct sockaddr *) &serv_addr, sizeof(serv_addr)) < 0) {
perror("connect");
exit(1);
}
char buffer[1024];
strcpy(buffer, "Hello, server!");
//发送数据, 已经connect了,就不用带服务器地址了.
int n = send(sockfd, buffer, strlen(buffer), 0);
if (n == -1) {
perror("send");
exit(1);
}
//接受数据
n = recv(sockfd, buffer, 1024, 0);
if (n == -1) {
perror("recv");
exit(1);
}
printf("Received: %s\n", buffer);
close(sockfd);
return 0;
}
结果展示:
./tcp_send 127.0.0.1
Received: Hello, client!
./server
Received: Hello, server!
Received: Hello, server!