1、 请指出MAC地址、IPv4、IPv6和端口各占多少位?如何获取本机的MAC地址和IP地址?
IPv4的端口占32位;
IPv6的端口占128位;
MAC的地址占48位;
在OSI模型中,第三层网络层负责IP地址,第二层数据链路层负责MAC地址,因此一个主机会有一个MAC地址,而每个网络位置会有一个专属它的IP地址;
在系统管理界面中,使用ipconfig /all命令可以获得MAC地址。
2、 编程实现将字符串表示的IP地址转换为32位的无符号整数,例如192.168.1.100的无符号整数表示为0xc0a80164。
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
unsigned int ip_addr(const char *ip)
{
int a, b, c, d;
if (sscanf(ip, "%d.%d.%d.%d", &a, &b, &c, &d) == 4)
{
return (a << 24) | (b << 16) | (c << 8) | d;
}
return 0;
}
int main()
{
printf("0x%08X\n", ip_addr("192.168.1.100"));
return 0;
}
3、 编程实现将32位的无符号整数表示的IP地址转换为点字符串表示的IP地址。
#include <cstdio>
#include <cmath>
#include <vector>
#define IP 4 //IP version 4
#define BASE 2.0 // binary
#define BIT 8
using namespace std;
int main()
{
unsigned int num;
scanf("%d", &num);
int ipv = IP;
vector<int> ipvec;
while(ipv--) {
int bits = BIT;
int digit = 0;
while(bits--) {
int b = num % 2;
num /= 2;
if(b != 0) {
digit += pow(BASE, (BIT - bits - 1));
}
printf("%d\n", digit);
}
ipvec.push_back(digit);
}
for (int i = ipvec.size() - 1; i >=0; i--) {
printf("%d", ipvec[i]);
if(i != 0) {
printf(".");
}
}
return 0;
}
4、 编写一个C程序计算192.168.1.100/27表示的IP主机所在网络可能的主机地址范围。
#include <stdio.h>
#include <winsock.h>
#include <string.h>
int getnum(char *p1)
{
char *p;
int num;
while(p1!=NULL)
{
p1 = strstr(p1,”/”);
if(p1 != NULL)
{
p = p1 + 1 //此处p位“27”的首地址
}
}
num = (*p -48) * 10 + (*(p + 1) – 48);
return num;
}
char *get_ip(char *p1)
{
int i = 0;
char *ip_str;
//得到ip_str
while(p1 != NULL)
{
p1 != ‘/’;
*(ip_str+i) = *p1;
p1++;
i++
}
*(ip_str+i) = 0;
i = 0;
return ip_str;
}
unsigned int ip_addr(const char *ip)
{
int a, b, c, d;
if (sscanf(ip, "%d.%d.%d.%d", &a, &b, &c, &d) == 4)
{
return (a << 24) | (b << 16) | (c << 8) | d;
}
return 0;
}
int main()
{
int ip_num = 0;
int num = 0;
int ip_min = 0;
num = getnum (“192.168.1.100/27”);
ip_num = ip_addr(get_ip(“192.168.1.100/27”));
ip_min = ip_num & ((ip_num >> (32 - num)) << (32 - num));
ip_max = ip_min | ((unsigned int)0xff >> num);
printf(“最小ip为:%s\n”,inet_ntoa(ip_min));
printf(“最大ip为:%s\n”,inet_ntoa(ip_max));
return 0;
}
5、请仔细阅读下列程序,然后回答问题。
#include <stdio.h>
int main() {
char doc[ ] = “d:/mydoc/my.doc”,
char *p = doc; char *p1 = p;
while(p1!=NULL) {
p1 = strstr(p, "/");
if(p1!=NULL) p = p1+1
}
printf("%s\n", p);
}
该程序的主要功能是什么?程序的输出结果是什么?函数strstr的作用是什么?
该程序的主要功能:寻找字符段,该字符段有如下特点:字符段前有‘/’,字符段后无‘/’;
程序输出结果:my.doc
strstr的作用:找到‘/’所在位置。
6、 请指出strcpy和memcpy两个函数在使用上的区别是什么?
strcpy:char *strcpy(char *dest, const char *src);
功能:把从src地址开始且含有NULL结束符的字符串复制到以dest开始的地址空间;
memcpy:void *memcpy(void *dest, const void *src, size_t n);
功能:从源src所指的内存地址的起始段位置开始拷贝n个字符串到目标dest所指的内存地址的起始位置。
区别:
1. 返回值类型不同;
2. 形参个数不同;
3. 函数功能不同。