用c语言写出 一个进程循环收, 另一个进程循环发(发送端进程将ip 地址和端口号用参数传入) 发送端,键盘输入输入 接收端,打印对方的ip地址和内容
时间: 2024-10-08 09:23:38 浏览: 31
在C语言中编写这样的程序需要使用到`stdio.h`, `sys/socket.h`, `netinet/in.h`, 和 `arpa/inet.h` 等头文件,以及创建socket、绑定、监听、接收和发送数据的基本网络编程知识。这里提供一个简单的示例,分为发送端和接收端两个部分:
**发送端 (sender.c)**
```c
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#define PORT 9000
#define MAX_BUF 100
int main(int argc, char *argv[]) {
if (argc != 3) {
printf("Usage: %s <IP> <PORT>\n", argv[0]);
return -1;
}
int sock = socket(AF_INET, SOCK_STREAM, 0);
struct sockaddr_in server_addr;
bzero(&server_addr, sizeof(server_addr));
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(atoi(argv[2]));
inet_aton(argv[1], &server_addr.sin_addr);
if (connect(sock, (struct sockaddr *)&server_addr, sizeof(server_addr)) < 0) {
perror("Connect failed");
return -1;
}
while (1) {
char input[MAX_BUF];
printf("Enter data to send: ");
fgets(input, MAX_BUF, stdin);
input[strcspn(input, "\n")] = '\0'; // Remove newline character
send(sock, input, strlen(input), 0);
printf("Data sent: %s\n", input);
}
close(sock);
return 0;
}
```
**接收端 (receiver.c)**
```c
#include <stdio.h>
#include <string.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#define PORT 9000
#define MAX_BUF 100
int main() {
int sock = socket(AF_INET, SOCK_STREAM, 0);
struct sockaddr_in server_addr;
bzero(&server_addr, sizeof(server_addr));
server_addr.sin_family = AF_INET;
server_addr.sin_addr.s_addr = htonl(INADDR_ANY);
server_addr.sin_port = htons(PORT);
if (bind(sock, (struct sockaddr *)&server_addr, sizeof(server_addr)) < 0) {
perror("Bind failed");
return -1;
}
listen(sock, 5); // Listening for incoming connections
while (1) {
struct sockaddr_in client_addr;
socklen_t addr_len = sizeof(client_addr);
int new_sock = accept(sock, (struct sockaddr *)&client_addr, &addr_len);
char buffer[MAX_BUF];
ssize_t bytes_received;
do {
bytes_received = recv(new_sock, buffer, MAX_BUF, 0);
buffer[bytes_received] = '\0';
printf("Received from %s:%d: %s\n", inet_ntoa(client_addr.sin_addr), ntohs(client_addr.sin_port), buffer);
} while (bytes_received > 0);
close(new_sock);
}
close(sock);
return 0;
}
```
要运行这个程序,先编译发送端(例如:`gcc sender.c -o sender`),然后提供IP地址和端口号作为命令行参数,如`./sender 127.0.0.1 9000`。然后启动接收端,它会监听并处理来自发送端的数据。
阅读全文