c socket编程

admin 40 0

在C语言中,Socket编程是一种通过网络进行通信的方式,它允许不同的计算机或进程之间进行数据交换,下面是一个简单的Socket编程示例,展示了如何使用C语言进行基本的Socket编程。

### 服务器端

```c

#include

#include

#include

#include

#include

#include

#define PORT 8080

int main() {

int server_fd, new_socket;

struct sockaddr_in address;

int addrlen = sizeof(address);

char buffer[1024] = {0};

char *message = "Hello from server";

// 创建socket

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(PORT);

// 绑定socket到端口8080

if (bind(server_fd, (struct sockaddr *)&address, sizeof(address)) < 0) {

perror("bind failed");

// 监听连接请求

if (listen(server_fd, 3) < 0) {

perror("listen failed");

printf("Server is listening on port %d\n", PORT);

// 接受客户端连接请求并发送消息

if ((new_socket = accept(server_fd, (struct sockaddr *)&address, (socklen_t*)&addrlen)) < 0) {

perror("accept failed");

send(new_socket, message, strlen(message), 0);

printf("Message sent\n");

// 接收客户端消息并打印出来

int valread = read(new_socket, buffer, 1024);

printf("Client message: %s\n", buffer);

close(new_socket);

close(server_fd);

return 0;

}

```

### 客户端端

#include // for read and write operations on sockets.h functions.

#include // for hostent structure and herror() function.

#include // for socklen_t type and socklen_t parameter of accept() function.

#include // for O_* constants as arguments of open() function.

#include // for iovec structure and writev() function.

#include // for inet_*() functions and inet_ntoa() function.

#include // for unix domain sockets.

#include // for ftime() function and timeb structure.

#include // for CLOCKS_PER_SEC macro and times() function.

#include // for MAXPATHLEN constant.

#include // for mode constants as arguments of open() function and st_* structure members.

#include // for waitpid() function and W_* constants returned by waitpid().

#include // for group structure and gr_*() functions and GR_* constants returned by getgrnam().

#include // for passwd structure and pw_*() functions andPW_* constants returned by getpwnam().

#include // for c_lflag field of termios structure and tcsetattr() function.

#include // for glob_*() functions and GLOB_* constants returned by