-2

I got the source port No. in hexa decimal no from the for loop as show in the code.. The Source port is 01 bb in this case.. I want to show it as 443 i.e. decimal how to show that...

printf("\nSource Port Number: ");
a = packet[34];
b = packet[35];
char num[20];
int num3;

strcpy (num, a);
strcat (num, b);
printf("Hexadecimal string %s\n", num);
sscanf(num,"%x", &num3);
printf("Decimal number %d\n", num3);

34 and 35 no. packet show the source port no. I have seen it from wireshark...I am getting 01 bb as the answer but i want to get it in decimal...

  • 4
    I don't see a for loop. I don't understand the question. – Paul Ogilvie May 27 '19 at 11:44
  • 2
    So the `printf("Decimal number...` isn't giving you a decimal output? The question isn't making sense. Please ask a specific question regarding the behavior of the specific code you are showing. – lurker May 27 '19 at 12:26

1 Answers1

0

You try to convert the port number which consists of data bytes '0x01 0xbb' captured by libpcap to integer value using sscanf. This won't work because sscanf expects the port number as character string "01bb". If you check the return value of sscanf i would expect it is '0' which means nothing happened because of expected data to format mismatch. I think you could setup the port number just by combining the data bytes '0x01' and '0xbb' using bitwise or and shift (Important: byte order).

Mathias Schmid
  • 431
  • 4
  • 7
  • a = packet[34]; b = packet[35]; char num[20]; int num3; num3 = a<<2 | b; printf("%d", num3); When I tried this it is showing 191 as the number but it is 443 so now what is the error in this then.. – vaibhav sharma May 28 '19 at 06:17
  • You need to shift a by 8 bit. I don't know what data type is a and b in your example but i assume it's char. So, you need at least cast 0xbb to unsigned char to avoid getting a negative result. num3 = ((int)((unsigned char)a)) << 8; num3 |= (int)((unsigned char)b); – Mathias Schmid May 28 '19 at 08:16
  • Fine. This solution works but contains a lot of casts. So, review your code and check if it's possible to reduce it. It's also worth to check for other solutions to pick port number from packet. Make sure you can trust the packet structure when you access it by fix offsets. – Mathias Schmid May 28 '19 at 12:39