在LINUX下如何编程设置系统时间和IP地址????

jun_zi913 2002-10-10 06:50:55
在Redhat7.2下如何编程设置系统时间
和IP地址,设置IP后可以重新启动???
请高手指点,谢谢。
...全文
514 11 打赏 收藏 转发到动态 举报
写回复
用AI写文章
11 条回复
切换为时间正序
请发表友善的回复…
发表回复
wmrwinhap 2002-11-22
  • 打赏
  • 举报
回复
gz
blh 2002-10-10
  • 打赏
  • 举报
回复
用上面的方法只能创建暂时的ip地址。如果希望创建永久的,需要创建/etc/sysconfig/network-scripts/ifcfg-eth0文件,内容如下
DEVICE=eth0
BROADCAST=192.168.200.255
IPADDR=192.168.200.200
NETMASK=255.255.255.0
NETWORK=192.168.200.0
ONBOOT=no
~
~
~
~
blh 2002-10-10
  • 打赏
  • 举报
回复
1.设置系统时间
#include <stdio.h>
#include <errno.h>
#include <time.h>
#include <sys/types.h>
#include <sys/time.h>

int set_date(struct tm *p_tm)
{
time_t when;
struct timeval tv;

when = mktime(p_tm);
if (when == -1)
return -1;
tv.tv_sec = when;
tv.tv_usec = 0;
return settimeofday(&tv, (struct timezone *)0);
}

int main()
{
struct tm tm;
// 1976年11月26日 11:15:0
memset(&tm, 0, sizeof(tm));
tm.tm_sec = 0;
tm.tm_min = 15;
tm.tm_hour = 11;
tm.tm_mday = 26;
tm.tm_mon = 10;
tm.tm_year = 1976 - 1900;
if (set_date(&tm) == -1)
perror("set_date");
return 0;
}

2。设置ip地址
#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/ioctl.h>
#include <netinet/in.h>
#include <fcntl.h>
#include <errno.h>
#include <net/if.h>


int ifconfig(const char *ifname, const char *ipaddr)
{
struct sockaddr_in sin;
struct ifreq ifr;
int fd;

int ret;
char *ptr;
short found_colon = 0;

bzero(&ifr, sizeof(struct ifreq));
if (ifname == NULL)
return (-1);
if (ipaddr == NULL)
return (-1);

fd = socket(AF_INET, SOCK_DGRAM, 0);
if (fd == -1)
{
perror("Not create network socket connection\n");
return (-1);
}

strncpy(ifr.ifr_name, ifname, IFNAMSIZ);
ifr.ifr_name[IFNAMSIZ - 1] = 0;
memset(&sin, 0, sizeof(sin));
sin.sin_family = AF_INET;
sin.sin_addr.s_addr = inet_addr(ipaddr);
memcpy(&ifr.ifr_addr, &sin, sizeof(sin));

if (ioctl(fd, SIOCSIFADDR, &ifr) < 0)
{
perror("Not setup interface\n");
return (-1);
}

ifr.ifr_flags |= IFF_UP | IFF_RUNNING;

if (ioctl(fd, SIOCSIFFLAGS, &ifr) < 0)
{
perror("SIOCSIFFLAGS");
return (-1);
}
return (0);
}

//Usage setip eth0 xxx.xxx.xxx.xxx
int main(int argc, char *argv[])
{
ifconfig(argv[1], argv[2]);
return 0;
}


fwbmail 2002-10-10
  • 打赏
  • 举报
回复
settime()设置时间
gongdath 2002-10-10
  • 打赏
  • 举报
回复
实在不行的话可以使用system调用date设置时间.
但我不知道如何设置IP.
gongdath 2002-10-10
  • 打赏
  • 举报
回复
他是说要在程序中实现.
不是SHELL.
mr_fanwei 2002-10-10
  • 打赏
  • 举报
回复
up
jspxnet 2002-10-10
  • 打赏
  • 举报
回复
linuxconf
peakcn 2002-10-10
  • 打赏
  • 举报
回复
设置时间:date
设置IP:ifconfig

很多地方和书里写的很详细呀
gongdath 2002-10-10
  • 打赏
  • 举报
回复
可以使用SETCLOCK设置时间.
newsoldier 2002-10-10
  • 打赏
  • 举报
回复
在终端输入setup,根据选项选择进行配置

23,124

社区成员

发帖
与我相关
我的任务
社区描述
Linux/Unix社区 应用程序开发区
社区管理员
  • 应用程序开发区社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧