ILD

qemu enable network
作者:Yuan Jianpeng 邮箱:yuanjp89@163.com
发布时间:2026-5-27 站点:Inside Linux Development

最近想通过ssh开启远程终端。因此需要打开网络功能。


1 guest内核开启相关选项

开启TCP/IP

+CONFIG_INET=y

+# CONFIG_IPV6 is not set


开启网卡驱动

+CONFIG_NETDEVICES=y

+CONFIG_VIRTIO_NET=m


2 qemu命令行开启网络选项

首先需要开启网卡设备:

-device virtio-net,netdev=net0


其次,配置宿主机网络,有很多种模式。

这两个是一对。通过netdev=net0,下面的id=net0,成对。


user模式

-netdev user,id=net0,net=192.168.76.0/24,hostfwd=tcp::8023-:23

user模式下,在host里面没有额外的接口。guest使用nat访问。如果host要访问guest的某个端口,需要开启端口映射,如上的8022-22


guest可以通过dhcp拨号:

# modprobe virtio-net
# ifconfig eth0 up

# udhcpc -i eth0
udhcpc: started, v1.36.1
udhcpc: broadcasting discover
udhcpc: broadcasting select for 192.168.76.15, server 192.168.76.2
udhcpc: lease of 192.168.76.15 obtained from 192.168.76.2, lease time 86400

# ifconfig eth0 192.168.76.15
# ip route add default via  192.168.76.2
# ping 8.8.8.8
PING 8.8.8.8 (8.8.8.8): 56 data bytes
64 bytes from 8.8.8.8: seq=0 ttl=255 time=84.848 ms


host访问guest的telnet

telnet 127.0.0.1 8023


user模式可能有防火墙问题,在我的ubuntu26.04上,telnet只能建立tcp连接,但是后续不通。


tap模式

tap模式,在host和guest各有一个接口,注意:tap是L2模式,tun是L3模式。所以tap的两个接口并不是点不点的。

-netdev tap,id=net0,ifname=tap0,script=no,downscript=no


host配置

需要再host创建tap接口,这需要root权限,创建后可以配置IP

# sudo ip tuntap add dev tap0 mode tap user yuanjp
# sudo ip link set tap0 up
# sudo ifconfig tap0 192.168.76.1



guest配置

# modprobe virtio-net
# ifconfig eth0 up
# ifconfig eth0 192.168.76.2


此时在host里面可以直接ping guest手动配置的IP

$ ping 192.168.76.2

PING 192.168.76.2 (192.168.76.2) 56(84) bytes of data.

64 bytes from 192.168.76.2: icmp_seq=1 ttl=64 time=1.82 ms

64 bytes from 192.168.76.2: icmp_seq=2 ttl=64 time=1.03 ms

64 bytes from 192.168.76.2: icmp_seq=3 ttl=64 time=0.730 ms


还有一些其它的模式。


参考:

https://github.com/HathewayWill/Ubuntu_Server_QEMU_Guide





Copyright © linuxdev.cc 2017-2024. Some Rights Reserved.