插件窝 干货文章 ifconfig命令如何设置IP地址

ifconfig命令如何设置IP地址

ifconfig 接口 sudo 115    来源:    2025-05-09

ifconfig 是 Linux/Unix 系统中用于配置网络接口的传统命令(现逐渐被 ip 命令取代)。以下是使用 ifconfig 设置 IP 地址的详细步骤和注意事项:


1. 基本语法

sudo ifconfig <接口名> <IP地址> netmask <子网掩码>

示例:将 eth0 的 IP 设置为 192.168.1.100,子网掩码 255.255.255.0

sudo ifconfig eth0 192.168.1.100 netmask 255.255.255.0

2. 可选参数

  • 设置网关(需配合 route 命令):

    sudo route add default gw <网关IP> <接口名>
    

    示例:

    sudo route add default gw 192.168.1.1 eth0
    
  • 启用/禁用接口

    sudo ifconfig eth0 up    # 启用
    sudo ifconfig eth0 down  # 禁用
    

3. 设置临时 vs 永久

  • 临时生效
    通过 ifconfig 设置的 IP 会在重启后失效,仅用于临时调试。

  • 永久生效
    需修改网络配置文件(不同系统路径不同):

    • Ubuntu/Debian/etc/network/interfaces
    auto eth0
    iface eth0 inet static
        address 192.168.1.100
        netmask 255.255.255.0
        gateway 192.168.1.1
    
    • RHEL/CentOS/etc/sysconfig/network-scripts/ifcfg-eth0
      修改后重启网络服务:
    sudo systemctl restart network
    

4. 注意事项

  1. 需要 root 权限:使用 sudo 或切换到 root 用户。
  2. 接口名确认:通过 ifconfig -aip link show 查看可用接口。
  3. 替代命令:现代系统推荐使用 ip 命令(功能更强大): bash sudo ip addr add 192.168.1.100/24 dev eth0
  4. 冲突风险:确保设置的 IP 未被其他设备占用。

5. 验证配置

ifconfig eth0  # 检查IP是否生效
ping 8.8.8.8   # 测试网络连通性

如果遇到问题,可能是防火墙、路由或接口未启用导致,需进一步排查。