在linux下c编程怎么得到主机名

在linux下c编程怎么得到主机名,第1张

c语言本身是不提供的。

在windows下使用系统命令或windows.h

//列子

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

#include "stdio.h"

#include "conio.h"

main()

{

int i,j

char ip[20]

char temp[100]

char ch='\0'

FILE *fp

system("ipconfig >d:\\myip.txt")

if ((fp=fopen("d:\\myip.txt","r"))==NULL)

{

printf("the file can not open:\nPress any key to exit:")

getch()

exit(1)

}

for (i=0i<7i++)

{fgets(temp,80,fp)/*跳过一些行*/

/*printf("%s\n",temp)*/}

fgets(temp,80,fp)

i=0j=0

while (temp[i++]!=':')

while (temp[i]!='\n')

ip[j++]=temp[i++]

ip[j]=0

printf("IP=%s\n",ip)

fclose(fp)

system("del d:\\myip.txt")

4.2如何察看本机的MAC地址 这个.....最简单明了的方法..... 就是拔出网卡,直接在网卡上寻找(网卡制造商通常都会把网卡的MAC地址标识在网卡上面) 如果不方便的,我们可以在不同的OS下面通过一些简单的命令察看到网卡的MAC地址 Windows类 对于win98/winme 开始-->运行-->winipcfg 对于win2k/xp/2003 命令行下 ipconfig /all 显示结果中的Phyical Address即为需要寻找的MAC地址 UNIX类 对于Linux使用ifconfig命令 # ifconfig -a eth0 Link encap:Ethernet HWaddr 00:60:08:C4:99:AA inet addr:131.225.84.67 Bcast:131.225.87.255 Mask:255.255.248.0 UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1 RX packets:15647904 errors:0 dropped:0 overruns:0 TX packets:69559 errors:0 dropped:0 overruns:0 Interrupt:10 Base address:0x300 //HWAddr后面那串数值就是MAC地址 对于Solaris同样也是ifconfig -a # ifconfig -a le0: flags=863 mtu 1500 inet 131.225.80.209 netmask fffff800 broadcast 131.225.87.255 ether 8:0:20:10:d2:ae //ether后面那串数值 对于FreeBSD而言使用dmesg命令 对于HPUX机器使用lanscan命令 $ lanscan Hardware Station Dev Hardware Net-Interface NM Encapsulation Mjr Path Address lu State NameUnit State ID Methods Num 2.0.2 0x08000935C99D 0 UP lan0 UP 4 ETHER 52 4.3如何察看远程主机的MAC地址 分成两种情况 1.同一网段 先ping一下对端主机 然后通过arp -a可以察看到相应主机的mac地址 例如: C:\Documents and Settings\Administrator>arp -a Interface: 10.1.7.88 --- 0x4 Internet Address Physical Address Type 10.1.7.250 00-0a-eb-cb-ca-c0 dynamic 2.不同网段 nbtstat -a ip-address 但是前提是对端为windows主机同时打开了相应的端口 本地连接: Node IpAddress: [10.1.7.88] Scope Id: [] NetBIOS Remote Machine Name Table Name Type Status --------------------------------------------- INet~Services <1C>GROUP Registered IS~SOFTLORD....<00>UNIQUE Registered SOFTLORD <00>UNIQUE Registered WORKGROUP <00>GROUP Registered ADMINISTRATOR <03>UNIQUE Registered WORKGROUP <1E>GROUP Registered SOFTLORD <20>UNIQUE Registered IWAM_

可以使用getuid()获取用户的ID号,然后通过getpwuid函数通过用户的uid查找用户的passwd数据来获取系统登录的用户名。

#include <stdio.h>

#include <pwd.h>

#include <unistd.h>

int main(void)

{

struct passwd *pwd

pwd = getpwuid(getuid())

printf("当前登陆的用户名为:%s\n", pwd->pw_name)

return 0

}


欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/yw/8990370.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-04-23
下一篇 2023-04-23

发表评论

登录后才能评论

评论列表(0条)

保存