Tag Archives: shell

get my ip address useing c / sample code

C CODE

902c2c377de669ec360e37664cc1f041

/*
  FILENAME : my_local_ip.c
*/
#include
#include
#include
#include
#include
#include
#include
#include 

int main(int argc, char **argv) {
  int s;
  struct sockaddr_in sin;
  int slen;
  int port;

  if( argc<3 ) {
    printf("Usage: %s  \n", argv[0]);
    printf("\n\tsample %s 203.66.88.89 80\n",argv[0]);
    return -1;
  }

  port = atoi(argv[2]);

  s = socket(PF_INET, SOCK_STREAM, 0);
  memset(&sin, 0, sizeof(sin));
  sin.sin_family = PF_INET;
  sin.sin_port = htons(port);
  sin.sin_addr.s_addr = inet_addr(argv[1]);
  if(connect(s, (struct sockaddr *)&sin, sizeof(sin)) < 0) {
    printf("127.0.0.1");
    return -1;
  }

  memset(&sin, 0, sizeof(sin));
  slen = sizeof(sin);
  if(getsockname(s, (struct sockaddr *)&sin, &slen) < 0) {
    printf("127.0.0.1");
    close(s);
    return -1;
  }

  printf("%s", inet_ntoa(sin.sin_addr));

  close(s);
  return 0;
}

可以依自己的需求來改這SHELL:

#!/bin/sh
ADDR=`my_local_ip 168.95.1.1 53`
FILENAME=${ADDR=}".txt"

echo $FILENAME