c语言实现tcp客户端
时间: 2023-10-05 10:13:39 浏览: 77
以下是一个简单的TCP客户端实现,该程序可以连接到指定的服务器并发送数据:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
int main(int argc, char *argv[]) {
if (argc < 3) {
fprintf(stderr, "usage: %s <ip_address> <port>\n", argv[0]);
exit(EXIT_FAILURE);
}
const char *ip = argv[1];
int port = atoi(argv[2]);
// 创建TCP套接字
int sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0) {
perror("socket");
exit(EXIT_FAILURE);
}
// 设置服务器地址信息
struct sockaddr_in servaddr;
memset(&servaddr, 0, sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_port = htons(port);
if (inet_pton(AF_INET, ip, &servaddr.sin_addr) <= 0) {
perror("inet_pton");
exit(EXIT_FAILURE);
}
// 连接服务器
if (connect(sockfd, (struct sockaddr *)&servaddr, sizeof(servaddr)) < 0) {
perror("connect");
exit(EXIT_FAILURE);
}
// 发送数据
char buf[1024];
printf("Please input message: ");
if (fgets(buf, sizeof(buf), stdin) != NULL) {
size_t len = strlen(buf);
if (buf[len - 1] == '\n') {
buf[len - 1] = '\0';
}
if (write(sockfd, buf, len) < 0) {
perror("write");
exit(EXIT_FAILURE);
}
}
// 关闭套接字
close(sockfd);
return 0;
}
```
在命令行中运行该程序时需要提供两个参数:服务器的IP地址和端口号。例如:
```
$ ./client 127.0.0.1 8888
Please input message: Hello, server!
```
该程序首先创建一个TCP套接字,然后设置服务器地址信息,并连接到服务器。之后,程序等待用户输入数据并通过TCP连接发送给服务器。最后,程序关闭套接字并退出。
阅读全文
相关推荐
















