Qemu套接字通信

问题描述

我正在尝试使用套接字在服务器(在Qemu上使用Cortex-A53 cpu在Ubuntu上运行)和客户端(在我的pc上的CentOS上运行)之间进行简单的通信。

如果我仅从Centos(client.c和server.c)运行C ++代码,则可以正常工作。如果两个都从Ubuntu运行,则相同。但是,如果我从Ubuntu启动server.c,从CentOS启动client.c,则通讯将无法进行。

我正在使用的C代码来自本教程: https://www.geeksforgeeks.org/socket-programming-cc/

Qemu命令:

qemu-system-aarch64 -m 2048 -smp 2 -cpu cortex-a53 -M virt -nographic   \
        -pflash flash0.img   \
        -pflash flash1.img   \
        -drive if=none,file=${IMAGE},format=qcow2,id=hd0 -device virtio-blk-device,drive=hd0   \
        -drive if=none,id=cloud,file=cloud.img,format=qcow2 \
        -device virtio-blk-device,drive=cloud   \
        -device virtio-net-device,netdev=user0 \
        -netdev user,id=user0,hostfwd=tcp::10022-:22  \
        -device virtio-serial \
        -chardev socket,id=foo,host=localhost,port=8080,server,Nowait \
        -device virtserialport,chardev=foo,name=test0 

当我从Qemu运行server.c而从我的PC运行client.c时。我看到server.c在accept()函数处被阻止,而client.c在read()函数处被阻止。

如果我在Ubuntu上运行以下命令: $ sudo lsof -i -P -n | grep LISTEN我明白了:

systemd-r   644 systemd-resolve   13u  IPv4  15994      0t0  TCP 127.0.0.53:53 (LISTEN)
sshd        745            root    3u  IPv4  18696      0t0  TCP *:22 (LISTEN)
sshd        745            root    4u  IPv6  18699      0t0  TCP *:22 (LISTEN)
server    14164            root    3u  IPv4  74481      0t0  TCP *:8080 (LISTEN)

如果我在CentOS上运行相同的命令,则会得到以下信息:

qemu-syst 57073 ibestea   10u  IPv4 2648807035      0t0  TCP 127.0.0.1:8080 (LISTEN)
qemu-syst 57073 ibestea   13u  IPv4 2648807037      0t0  TCP *:10022 (LISTEN)

欢迎任何帮助。

解决方法

问题是我试图通过使用主机地址和端口从服务器部分连接到套接字,但是要访问Qemu数据,我必须使用文件描述符/ dev / vport3p1连接到套接字。

server.c文件应类似于以下内容:

#include <unistd.h>
#include <stdio.h>
#include <sys/socket.h>
#include <stdlib.h>
#include <netinet/in.h>
#include <string.h>

#include <fcntl.h>
#include <string.h>
#include <signal.h>
#include <sys/ioctl.h>

#define PORT 8080
#define DEV_PATH "/dev/vport3p1"

int main(int argc,char const *argv[])
{
    int server_fd,new_socket,valread;
    struct sockaddr_in address;
    int opt = 1;
    int addrlen = sizeof(address);
    char buffer[1024] = {0};
    char *hello = "Hello from server";
    int     dev_fd;

    printf("SERVER: get an internet domain socket\n");
    if ((dev_fd = open(DEV_PATH,O_RDWR)) == -1) {
        perror("open");
                exit(1);
    }
    else {
        printf("SERVER: opened file descriptor first time  = %d\n",dev_fd);
    }

    valread = read( dev_fd,buffer,1024);
    printf("%s\n",buffer );
    valread = write(dev_fd,hello,strlen(hello));
    printf("Hello message sent\n");
    return 0;
}