Linux Socket编程是一种网络通信机制,它允许不同计算机上的应用程序通过一个共同的协议进行数据交换。Socket API提供了一系列函数,用于创建、配置、连接、监听、发送和接收数据。
socket()
:创建一个新的socket。bind()
:将socket绑定到一个IP地址和端口上。listen()
:将socket设置为监听模式,等待连接请求。accept()
:接受一个来自客户端的连接请求。connect()
:客户端使用此函数连接到服务器。send()
/recv()
:发送和接收数据。close()
:关闭socket。原因:
解决方法:
bind()
函数,并指定了正确的IP地址和端口。netstat
或lsof
命令检查端口是否被占用。原因:
解决方法:
ping
或traceroute
命令检查网络连通性。以下是一个简单的TCP服务器和客户端的示例代码:
服务器端代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
int main() {
int server_fd, new_socket;
struct sockaddr_in address;
int addrlen = sizeof(address);
char buffer[1024] = {0};
const char *hello = "Hello from server";
// Creating socket file descriptor
if ((server_fd = socket(AF_INET, SOCK_STREAM, 0)) == 0) {
perror("socket failed");
exit(EXIT_FAILURE);
}
address.sin_family = AF_INET;
address.sin_addr.s_addr = INADDR_ANY;
address.sin_port = htons(8080);
// Binding the socket to the IP / port
if (bind(server_fd, (struct sockaddr *)&address, sizeof(address)) < 0) {
perror("bind failed");
exit(EXIT_FAILURE);
}
// Listening for incoming connections
if (listen(server_fd, 3) < 0) {
perror("listen");
exit(EXIT_FAILURE);
}
// Accepting a new connection
if ((new_socket = accept(server_fd, (struct sockaddr *)&address, (socklen_t*)&addrlen)) < 0) {
perror("accept");
exit(EXIT_FAILURE);
}
send(new_socket, hello, strlen(hello), 0);
printf("Hello message sent\n");
valread = read(new_socket, buffer, 1024);
printf("%s\n", buffer);
close(new_socket);
close(server_fd);
return 0;
}
客户端代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
int main() {
struct sockaddr_in serv_addr;
int sock = 0;
char buffer[1024] = {0};
const char *hello = "Hello from client";
if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
printf("\n Socket creation error \n");
return -1;
}
serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons(8080);
// Convert IPv4 and IPv6 addresses from text to binary form
if(inet_pton(AF_INET, "127.0.0.1", &serv_addr.sin_addr)<=0) {
printf("\nInvalid address/ Address not supported \n");
return -1;
}
if (connect(sock, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0) {
printf("\nConnection Failed \n");
return -1;
}
send(sock , hello , strlen(hello) , 0 );
printf("Hello message sent\n");
valread = read( sock , buffer, 1024);
printf("%s\n",buffer );
close(sock);
return 0;
}
请注意,以上代码仅用于演示目的,实际应用中需要考虑更多的错误处理和资源管理。
领取专属 10元无门槛券
手把手带您无忧上云