[英]How to read an IP Address in C (Windows)?
我發現int
數據類型可用於聲明數值范圍為-32,768 to 32,767
或-2,147,483,648 to 2,147,483,647
的數字/整數變量。
而char
數據類型可用於存儲-128 to 127 or 0 to 255
值。
IP地址呢? 我已經嘗試過int
但是只能識別IP的第一個八位字節。
char
也不能很好地工作。
代號
C:\Codes>more input_output.c
#include <stdio.h>
int main()
{
int a;
int b;
char c;
printf("\n1. Enter a number : ");
scanf("%d",&a);
printf("You've entered %d\n",a);
printf("\n2. Enter an IP Address : ");
scanf("%d",&b);
printf("You've entered %d\n",b);
printf("\n3. Enter an IP Address : ");
scanf("%c",&c);
printf("You've entered %d\n",c);
return 0;
}
C:\Codes>
編譯中
C:\Codes>gcc input_output.c -o input_output
C:\Codes>
最終輸出
C:\Codes>input_output.exe
1. Enter a number : 5
You've entered 5
2. Enter an IP Address : 8.8.8.8
You've entered 8
3. Enter an IP Address : You've entered 46
C:\Codes>
IP
地址是真正的32
位整數,通常以192.0.2.33
類的字符串形式表示。 它保存在struct sockaddr_in
。
最好的方法是使用專門的函數inet_pton
將您的字符串轉換為IP
地址,然后通過inet_ntop
將其取回。
#include <stdio.h>
#ifdef _WIN32
#include <winsock2.h>
#else
#include <sys/socket.h>
#include <netinet/in.h>
#include <netinet/ip.h>
#endif
int main (void)
{
int parts[4];
struct sockaddr_in sa;
char str[64];
// naive approach:
printf ("\n Enter 4 IP Address parts : \n");
scanf ("%d", &parts[3]);
scanf ("%d", &parts[2]);
scanf ("%d", &parts[1]);
scanf ("%d", &parts[0]);
printf ("%d.%d.%d.%d\n", parts[3], parts[2], parts[1], parts[0]);
// The best:
printf ("\n Enter IP Address in a format: 192.0.2.33 :\n");
scanf ("%s", str);
// store this IP address in sa:
inet_pton(AF_INET, str, &(sa.sin_addr));
// now get it back and print it
inet_ntop(AF_INET, &(sa.sin_addr), str, INET_ADDRSTRLEN);
printf("%s\n", str);
return 0;
}
輸出:
Enter 4 IP Address parts :
190
0
2
33
190.0.2.33
Enter IP Address in a format: 192.0.2.33 :
190.0.5.22
190.0.5.22
scanf("%d",&b);
掃描數字后停止(停止/不讀取以下點字符),但是您輸入8.8.8.8
下次掃描char
您將獲得的代碼.
( 點的 ASCII為46
)
在此問答中描述了讀取IP地址的正確方法: 在C中輸入IP地址
您了解字符串了嗎? 這些基本上是連續的許多字符。 您可以在C中編寫類似的內容。
const char* ip = "127.0.0.1"
或使用scanf讀取
char ip[256];
scanf("%s", ip);
char ip[256]
定義了一個char數組。 然后下一行scanf("%s", ip);
將從鍵盤輸入的任何內容讀入char數組。
僅僅因為一個ip地址中包含數字,並不意味着您應該使用整數進行存儲。 ip地址更像是電話號碼。 算術對他們沒有意義。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.