EMS/drv/drv_4g.c

126 lines
3.4 KiB
C
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#include "drv_4g.h"
#define BUFFER_SIZE 1024
#define LOCAL "10.244.216.42"
void client(char server_addr[], int server_port) {
int sock = 0;
// struct ifreq ifr;
char buffer[BUFFER_SIZE];
// 创建套接字
if ((sock = socket(AF_INET, SOCK_STREAM, 0)) == 0) {
perror("套接字创建失败");
exit(EXIT_FAILURE);
}
//************如果只绑定网卡名不能连接服务端可以同时绑定ip和网卡尝试一下************* */
// //local ip
// struct sockaddr_in local_addr;
// local_addr.sin_family = AF_INET;
// local_addr.sin_port = htons(0);
// local_addr.sin_addr.s_addr = inet_addr("10.232.226.30");
// // if (inet_pton(AF_INET, "192.168.2.190", &local_addr.sin_addr) <= 0) {
// // perror("无效的地址");
// // exit(EXIT_FAILURE);
// // }
// if (bind(sock, (struct sockaddr *)&local_addr, sizeof(local_addr)) < 0) {
// perror("bind失败");
// exit(EXIT_FAILURE);
// }
// else
// {
// printf("bind success\n");
// }
// else {
// printf("bind success!\n");
// }
// if ((sock = socket(AF_INET, SOCK_STREAM, 0)) == 0) {
// perror("套接字创建失败");
// exit(EXIT_FAILURE);
// }
// 设置要绑定的网卡接口名称
// strcpy(ifr.ifr_name, interface);
// // 将套接字绑定到指定的网卡
// if (setsockopt(sock, SOL_SOCKET, SO_BINDTODEVICE, &ifr, sizeof(ifr)) < 0) {
// perror("setsockopt");
// close(sock);
// exit(1);
// }
// else{
// printf("connect the local interface:%s\n", ifr.ifr_name);
// }
//绑定服务端的ip
// 设置服务器地址结构体
struct sockaddr_in serv_addr;
serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons(server_port);
serv_addr.sin_addr.s_addr = inet_addr(server_addr);
// 连接服务器
if (connect(sock, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0) {
perror("connect失败");
exit(EXIT_FAILURE);
}
else {
printf("connect success!\n");
}
// // 将服务器IP地址从点分十进制字符串转换为网络字节序
// if (inet_pton(AF_INET, "47.120.14.45", &serv_addr.sin_addr) <= 0) {
// perror("无效的地址");
// exit(EXIT_FAILURE);
// }
while (1)
{
// 输入要发送的数据
printf("请输入要发送的数据(输入'quit'退出):");
fgets(buffer, BUFFER_SIZE, stdin);
// 去除换行符
buffer[strcspn(buffer, "\n")] = 0;
if (strcmp(buffer, "quit") == 0) {
break;
}
// 向服务器发送数据
if (send(sock, buffer, strlen(buffer), 0) < 0) {
perror("发送数据失败");
break;
}
printf("已向服务端发送数据\n");
// 接收服务器返回的回复数据
memset(buffer, 0, BUFFER_SIZE);
if (recv(sock, buffer, BUFFER_SIZE, 0) < 0) {
perror("接收数据失败");
break;
}
if (strlen(buffer) == 0) {
// 服务器断开连接
printf("服务器已断开连接\n");
break;
}
printf("收到服务端回复:%s\n", buffer);
}
// 关闭套接字
close(sock);
}