Dear all,
I need to parse the http_proxy environmental variable in a linux C program.
Of course I do know how to retrieve the variable, but I am not sure that I correctly split the variable into parts. What I am interested at is the domain (or IP) part of the variable and the port.
So, my code (simplified of course) is:
Code:
unsigned int prxPort;
char *prxProtocol, *prxUsername, *prxPass, *prxHostname, *envProxySrv, *envSproxySrv;
envProxySrv=getenv("http_proxy");
parsePrxSrv(envProxySrv);
void parsePrxSrv(char *srv){
if(strstr(srv, "http")){
prxProtocol="http";
sscanf(srv, "http://%[^:]:%99d", prxHostname, &prxPort);
printf("Hostname: %s\n", prxHostname);
printf("Port: %d\n", prxPort);
}
}
In theory, that code should return the port and the hostname from the given URL. However, it prints:null, null:
Code:
Hostname: (null)
Port: 0
OK, hostname is: (null)Port: 0
Now, my questions:
1.
According to the sscanf(3) man page, the prxHostname should be given by reference, so the "correct" code should be:
Code:
sscanf(srv, "http://%[^:]:%99d", &prxHostname, &prxPort);
But, when I execute the program (and the compiler is not complained neither with warnings nor errors) I have a "segmentation fault" error when I reach he sscanf line. I believed that the reason for that is that I have not correctly initialize it, isn't it?
So, I made those initializations:
Code:
unsigned int prxPort;
char *prxProtocol, *prxUsername, *prxPass, *prxHostname, *envProxySrv, *envSproxySrv;
envProxySrv=getenv("http_proxy");
prxUsername="";
prxHostname="";
prxPass="";
prxProtocol="";
prxPort=8080;
parsePrxSrv(envProxySrv);
void parsePrxSrv(char *srv){
if(strstr(srv, "http")){
prxProtocol="http";
sscanf(srv, "http://%[^:]:%99d", prxHostname, &prxPort);
printf("Hostname: %s\n", prxHostname);
printf("Port: %d\n", prxPort);
}
}
Now, I had the segmentation fault either with the &prxHostname, or not. So, how do I correctly initialize it, it that is the problem of no parsing?
2. Why on earth isn't that code work?
PS I run the program in debug mode. Now, I set a watch on the envProxySrv variable and I see that the value is not the "pure" text that I would expect (http://192.168.0.1:3128), but the following:
0x7fffffffe6d3 "http://192.168.0.1:3128"
That is that hex at the start? Is this the reason why the parser is not working?