早上好,我完成了这段代码,其中的工作是将消息从pc1发送到pc3,中间有一个对话者(pc2)。当pc2从pc1接收消息时,它将发送pc的消息接收。当pc3收到消息时,它将为pc2发送确认,然后将确认发送到pc1。通过广播将消息从pc2发送到pc3。其他所有内容都是单播的,但是在我的代码中,我也通过广播将确认从pc2发送到了pc1。有人可以帮助我更改代码吗?谢谢。
pc2代码:
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <string.h>
#define exit_on_error(s,m) if (s < 0) { perror(m); exit(1); }
#define MAX_BUFFER 512
int main(int argc, char* argv[])
{
int sock, length, fromlen, r, send_sock, sendlen, V = 1, n; //int n declarado
struct sockaddr_in SERVER_ADDR;
struct sockaddr_in FROM_ADDR;
struct sockaddr_in SENDTO_ADDR;
//struct sockaddr_in LOCALMENTE_addr;
char buf[MAX_BUFFER];
//verifica argumentos
if (argc != 5)
{
printf("USAGE: %s <a.porto> <ip_broadcast> <c.porto> <b.porto>\n",argv[0]);
exit(1);
}
//cria socket UDP
sock = socket(AF_INET, SOCK_DGRAM, 0);
if(sock < 0) printf("SOCKET");
length = sizeof(SERVER_ADDR);
bzero(&SERVER_ADDR, length);
SERVER_ADDR.sin_family = AF_INET;
SERVER_ADDR.sin_addr.s_addr = INADDR_ANY;
SERVER_ADDR.sin_port = htons(atoi(argv[1]));
setsockopt(sock, SOL_SOCKET, SO_BROADCAST, &V, sizeof(V));
sendlen = sizeof(SENDTO_ADDR);
bzero(&SENDTO_ADDR, sendlen);
SENDTO_ADDR.sin_family = AF_INET;
SENDTO_ADDR.sin_addr.s_addr = inet_addr(argv[2]);
SENDTO_ADDR.sin_port = htons(atoi(argv[3]));
if(bind(sock, (struct sockaddr *)&SERVER_ADDR,length) < 0) printf("BIND: ");
fromlen = sizeof(struct sockaddr_in);
while(1)
{
printf("Wait for the next message...!\n");
bzero(&buf, MAX_BUFFER);
n = recvfrom(sock,buf,MAX_BUFFER,0,(struct sockaddr *) &FROM_ADDR, &fromlen);
if (strstr(buf,"Confirma")){
printf("Mensagem recebida: [%s], bytes recebidos: [%d]\n",buf,n);
SENDTO_ADDR.sin_addr.s_addr = inet_addr(argv[2]);
SENDTO_ADDR.sin_port = htons(atoi(argv[4]));
n = sendto (sock, buf,MAX_BUFFER,0,(struct sockaddr *) &SENDTO_ADDR, sendlen);
}
else{
printf("Mensagem recebida: [%s], bytes recebidos: [%d]\n",buf,n);
SENDTO_ADDR.sin_addr.s_addr = inet_addr(argv[2]);
SENDTO_ADDR.sin_port = htons(atoi(argv[3]));
n = sendto (sock, buf,MAX_BUFFER,0,(struct sockaddr *) &SENDTO_ADDR, sendlen);
SENDTO_ADDR.sin_addr.s_addr = inet_addr(argv[2]);
SENDTO_ADDR.sin_port = htons(atoi(argv[4]));
strcpy(buf," Confirmado interlocutor. ");
n = sendto (sock, buf,MAX_BUFFER,0,(struct sockaddr *) &SENDTO_ADDR, sendlen);
}
}
}