如何进行字符串处理? [英] How can I conduct the character strings?
问题描述
大家好.
我有一个关于字符串的问题.即:
我编写了一个应用程序来获取我的本地IP地址,例如192.168.0.35.但我想将其设为192.168.0.34.如何制作?
就是说,我要在获得的IP地址中减去我的最后一个数字.
//获得IP的应用程序代码:
Hello, everyone.
I have a question about character string. that is:
I write an application to get my local IP Address,such 192.168.0.35 . But I want to make it being 192.168.0.34.How can I make it ?
That is to say, I want to make my the last number minus one in the IP Address that I get.
//The application code getting IP:
#include"windows.h"
#include<stdlib.h>
#include<conio.h>
#pragma comment(lib,"ws2_32.lib")
void CheckIP(void) //define this function to get the local IP
{
WSADATA wsaData;
char name[255];
char *ip;
PHOSTENT hostinfo;
//MAKEWORD() to get the Winsock version
if ( WSAStartup( MAKEWORD(2,0), &wsaData ) == 0 )
{
if( gethostname ( name, sizeof(name)) == 0)
{
if((hostinfo = gethostbyname(name)) != NULL)
{
ip = inet_ntoa (*(struct in_addr *)*hostinfo->h_addr_list);
printf("\n\n Your IP is :%s\n\n",ip); //Output the IP Address
}
}
WSACleanup( ); //unload Winsock library
} }
int main(void)
{
CheckIP();
getch();
return 0;
}
例如:
我得到的本地IP .......我想要的字符串
192.168.0.35 ............. 192.168.0.34
192.168.5.62 ............. 192.168.5.61
192.168.12.09 ............. 192.168.12.08
有人可以帮我弄弦吗?请告诉我您的代码.
预先谢谢您.
for example:
the local IP I get ....... the string that I want
192.168.0.35 ............. 192.168.0.34
192.168.5.62 ............. 192.168.5.61
192.168.12.09 ............. 192.168.12.08
Could someone help me get the strings ? Please show me your code.
Thank you in advance.
推荐答案
如果它是字符串,例如
if it is a string, for instance
char sip[]= "192.168.0.35";
然后您可以做(错误处理留给读者...):
Then you may do (error handling left to the reader...):
int a,b,c,d;
char sip[] = "192.168.0.35";
char snewip[sizeof(sip)];
sscanf(sip,"%d.%d.%d.%d",&a,&b,&c,&d);
if (d>0) d--;
sprintf(snewip,"%d.%d.%d.%d",a,b,c,d);
为什么不从主机地址表中的相关字节值中减去1?请参见此处 [
Why not just subtract 1 from the relevant byte value in your host address table? See here[^] for details of the various returned structures.
这篇关于如何进行字符串处理?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!