I was looking at the std.socket and I was able to do the following to check the IP type but I can't find a way to get the byte array for the IP address.
auto results = getAddressInfo(ipaddress, AddressInfoFlags.NUMERICHOST);
if (results.length && results[0].family == AddressFamily.INET) {
writeln("IPv4 : " ~ results[0].address.toAddrString());
return 4;
}
else if (results.length && results[0].family == AddressFamily.INET6) {
writeln("IPv6 : " ~ results[0].address.toAddrString());
return 6;
}
I saw a couple of classes like InternetAddress and Internet6Address which have the addr() property that returns the byte array but I am not sure how to go from my code above to these 2 classes.
One way to do this is to get a pointer to the core.sys.posix.sys.socket.sockaddr structure using the Address.name.
Something like auto saddr_ptr = results[0].address.name; would do. Then you can extract the data you need by casting this pointer to a pointer of appropriate type (depending on the address family).
Here is a modified example from getAddress() documentation which uses sockaddr* to give you addresses as uint32_t values and conver them to ubyte[4] arrays:
module main;
import std.stdio;
import std.socket;
import std.c.linux.socket: sockaddr_in, in_addr;
void main(string[] args) {
// auto results = getAddressInfo("www.digitalmars.com");
try {
Address[] addresses = getAddress("dlang.org", 80);
writefln(" %d addresses found.", addresses.length);
foreach (int i, Address a; addresses) {
writefln(" Address %d:", i+1);
writefln(" IP address: %s", a.toAddrString());
writefln(" Hostname: %s", a.toHostNameString());
writefln(" Port: %s", a.toPortString());
writefln(" Service name: %s", a.toServiceNameString());
auto saddr_ptr = a.name;
auto in_ptr = *(cast(sockaddr_in*) saddr_ptr);
// let's convert it to ubyte[4] so we can access individual
// parts of the IPv4 address.
writeln(cast(ubyte[4])(in_ptr.sin_addr));
}
} catch (SocketException e) {
writefln(" Lookup error: %s", e.msg);
}
// Lets the user press <Return> before program returns
stdin.readln();
}
Output:
3 addresses found.
Address 1:
IP address: 162.217.114.56
Hostname: digitalmars.com
Port: 80
Service name: http
[162, 217, 114, 56]
Address 2:
IP address: 162.217.114.56
Hostname: digitalmars.com
Port: 80
Service name: http
[162, 217, 114, 56]
Address 3:
IP address: 162.217.114.56
Hostname: digitalmars.com
Port: 80
Service name: http
[162, 217, 114, 56]
Related
I have a basic task to connect some nodes to switch and let them communicate only with even-to-even and odd-to-odd IP addresses.
Scenario topology:
The starting point is an access network with full L2 connectivity based on a <DestMAC,OutputPort> table implemented on P4 switch.
Goal
Write a P4 code that creates two network slices, one enabling communication only between nodes with even IP addresses
and the other enabling communication only between nodes with odd IP addresses
header ipv4_t {
bit<4> version;
bit<4> ihl;
bit<8> diffserv;
bit<16> totalLen;
bit<16> identification;
bit<3> flags;
bit<13> fragOffset;
bit<8> ttl;
bit<8> protocol;
bit<16> hdrChecksum;
ip4Addr_t srcAddr;
ip4Addr_t dstAddr;
}
struct headers {
ethernet_t ethernet;
ipv4_t ipv4; //tay
}
/**SOME CODE*/
/*************************************************************************
************** I N G R E S S P R O C E S S I N G *******************
*************************************************************************/
control MyIngress(inout headers hdr,
inout metadata meta,
inout standard_metadata_t standard_metadata) {
action drop() {
mark_to_drop(standard_metadata);
}
action check_ip_odd_even(){
//TODO:
}
action forward_to_port(bit<9> egress_port) {
standard_metadata.egress_spec = egress_port;
}
table dmac_forward {
key = {
hdr.ethernet.dstAddr: exact;
}
actions = {
//ipv4_forward;
forward_to_port;
drop;
}
size = 8;
default_action = drop;
}
apply {
// if(hdr.ipv4.srcAddr & 1 == 1){
// //it's odd
// //dmac_forward.apply();
// }
// else {
// // it's even
// dmac_forward.apply();
// }
//10.0.0.13 vs 10.0.0.11
if (hdr.ipv4.srcAddr == 0x0a00000D && hdr.ipv4.dstAddr == 0x0a00000b){
dmac_forward.apply();
}
}
}
I tried to and with 1 so if it's 1 I would say it's odd but my solution didn't work. I also tried with exactly given IP addresses but this is not the general solution.
Any suggestion, please?
I am running the example sketches for a server and client:
Client:
/**
* Shared Drawing Canvas (Client)
* by Alexander R. Galloway.
*
* The Processing Client class is instantiated by specifying a remote
* address and port number to which the socket connection should be made.
* Once the connection is made, the client may read (or write) data to the server.
* Before running this program, start the Shared Drawing Canvas (Server) program.
*/
import processing.net.*;
Client c;
String input;
int data[];
void setup()
{
size(450, 255);
background(204);
stroke(0);
frameRate(5); // Slow it down a little
// Connect to the server's IP address and port
c = new Client(this, "127.0.0.1", 8080); // Replace with your server's IP and port
}
void draw()
{
if (mousePressed == true) {
// Draw our line
stroke(255);
line(pmouseX, pmouseY, mouseX, mouseY);
// Send mouse coords to other person
c.write(pmouseX + " " + pmouseY + " " + mouseX + " " + mouseY + "\n");
}
// Receive data from server
if (c.available() > 0) {
input = c.readString();
input = input.substring(0, input.indexOf("\n")); // Only up to the newline
data = int(split(input, ' ')); // Split values into an array
// Draw line using received coords
stroke(0);
line(data[0], data[1], data[2], data[3]);
}
}
Server:
/**
* Shared Drawing Canvas (Server)
* by Alexander R. Galloway.
*
* A server that shares a drawing canvas between two computers.
* In order to open a socket connection, a server must select a
* port on which to listen for incoming clients and through which
* to communicate. Once the socket is established, a client may
* connect to the server and send or receive commands and data.
* Get this program running and then start the Shared Drawing
* Canvas (Client) program so see how they interact.
*/
import processing.net.*;
Server s;
Client c;
String input;
int data[];
void setup()
{
size(450, 255);
background(204);
stroke(0);
frameRate(5); // Slow it down a little
s = new Server(this, 8080); // Start a simple server on a port
}
void draw()
{
if (mousePressed == true) {
// Draw our line
stroke(255);
line(pmouseX, pmouseY, mouseX, mouseY);
// Send mouse coords to other person
s.write(pmouseX + " " + pmouseY + " " + mouseX + " " + mouseY + "\n");
}
// Receive data from client
c = s.available();
if (c != null) {
input = c.readString();
input = input.substring(0, input.indexOf("\n")); // Only up to the newline
data = int(split(input, ' ')); // Split values into an array
// Draw line using received coords
stroke(0);
line(data[0], data[1], data[2], data[3]);
}
}
Now I think I should be able to inspect what the server is doing when I go to http://127.0.0.1:8080/. Unfortunately my browser seems to be unable to establish a connection with the server. Have I done something wrong and can it be fixed or are my expectations unrealistic?
The server and the client communicate via a network socket. They pass data in a format that is not understandable for your browser. The way to get the example to run is to launch the server first and the client second (you need to start the Processing environment two times). Now you should be able to draw lines on one side and see them being copied on the other side.
If you want to inspect what the server and client are doing, you can add println statements to the code.
The example code that you are using can be found here on GitHub:
https://github.com/processing/processing/tree/master/java/libraries/net/examples
I'm evaluating the use SQLite3 database for an application that needs to write log data. Randomly, reason why I'm not able to reproduce the issue, I'm facing app crash with segmentation fault. I succeeded to generate a SEGV dump which shows the following 2 traces:
1) sqlite3ExprListDup Trace
ip 0x7fff797b5b5d: _sigtramp+0x1d
ip 0x7fff787b11d7: sqlite3ExprListDup+0x127
ip 0x7fff787b5e62: sqlite3SelectDup+0x132
ip 0x7fff787848af: selectExpander+0x4df
ip 0x7fff787842f1: sqlite3WalkSelect+0x31
ip 0x7fff7885a87a: sqlite3SelectPrep+0x8a
ip 0x7fff7877a7be: sqlite3Select+0x28e
ip 0x7fff7874e28a: yy_reduce+0x10ca
ip 0x7fff7874b658: sqlite3RunParser+0x218
ip 0x7fff78749d0a: sqlite3LockAndPrepare+0x48a
ip 0x7fff787d61e7: sqlite3_prepare_v2+0xf7
ip 0x10ac75422: Connector::sqlite3Driver::executeDQL(std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const&)+0x82
2) sqlite3WhereBegin Trace
ip 0x7fff69eb5b5d: _sigtramp+0x1d
ip 0x7fff68e8b804: sqlite3WhereBegin+0x1424
ip 0x7fff68e7da0f: sqlite3Select+0x34df
ip 0x7fff68f6010f: multiSelectOrderBy+0xcef
ip 0x7fff68e7d24e: sqlite3Select+0x2d1e
ip 0x7fff68e7caaa: sqlite3Select+0x257a
ip 0x7fff68e4e28a: yy_reduce+0x10ca
ip 0x7fff68e4b658: sqlite3RunParser+0x218
ip 0x7fff68e49d0a: sqlite3LockAndPrepare+0x48a
ip 0x7fff68ed61e7: sqlite3_prepare_v2+0xf7
ip 0x100996432: Connector::sqlite3Driver::executeDQL(std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const&)+0x82
The first trace occurs on INSERT statements into table that contains 6 columns. I found on the Web similar cases (Firefox) resulting from a bug prior to SQlite version 3.18.x and that was corrected as from this version.
The second trace occurs on SELECT statement from the same table.
The environment is C++11 on MacOSX with sqlite-3.22.0 C API.
The log database is a one table structure which DDL is the following:
CREATE TABLE IF NOT EXISTS log (uuid TEXT NOT NULL
sourcename TEXT NOT NULL,
sourceipaddress TEXT NOT NULL,
stimestamp TEXT NOT NULL,
qtimestamp TEXT NOT NULL,
severity INTEGER NOT NULL,
content TEXT NOT NULL);
CREATE INDEX IF NOT EXISTS idx_uuid ON log (uuid);
CREATE INDEX IF NOT EXISTS idx_stimestamp ON log (stimestamp);
CREATE INDEX IF NOT EXISTS idx_qtimestamp ON log (qtimestamp);
CREATE INDEX IF NOT EXISTS idx_severity ON log (severity);
When inserting data into the log table, the app executes INSERT statements by lot (50 rows) using a wrapper and ensures TRANSACTION BEGIN and COMMIT/ROLLBACK:
[public] const bool Connector::open(const std::string& dbName, sqlite3 *dbConnection) {
int connStatus = sqlite3_open("log.db", &dbConnection);
if (connStatus == SQLITE_OK) {
return true;
... //Wrapper maintains the connection to the SQLite database
}
else {
return false;
}
}
[public] const bool Connector::startTransac() {
...
}
[public] const bool Connector::commitTransac() {
...
}
[public] const bool Connector::rollbackTransac() {
...
}
[public] const int Connector::executeDQL(const std::string& queryStmt) {
if (queryStmt.find("SELECT ") >= 0) {
sqlite3_stmt *statement = nullptr;
int sqLiteResult = sqlite3_prepare_v2(dbConnection, queryStmt.c_str(), -1, &statement, NULL);
if (sqLiteResult == SQLITE_OK) {
sqLiteResult = sqlite3_step(statement);
sqLiteResult = sqlite3_finalize(statement);
}
return sqLiteResult;
}
else {
return this->executeDML(queryStmt);
}
}
[public] const int Connector::executeDML(const std::string& queryStmt) {
char *errorMsg = 0;
int sqLiteResult = sqlite3_exec(dbConnection, queryStmt.c_str(), nullptr, nullptr, &_errorMessage);
if (sqLiteResult == SQLITE_OK) {
sqLiteResult = sqlite3_changes(dbConnection);
}
return sqLiteResult
}
Does anyone experienced the same and found a solution?
I am using Openstack Kilo and Terraform V 0.10
I need to attach multiple interfaces of same network to an instance.
I've tried the following attempts:
Adding network block three times in openstack_compute_instance_v2 using same network:
resource "openstack_compute_instance_v2" "VM`1" {
name = "VM1"
count = "1"
image_name = "image"
flavor_name = "flavor"
network = {
uuid = "${openstack_networking_network_v2.NET_1.id}"
}
network = {
uuid = "${openstack_networking_network_v2.NET_1.id}"
}
network = {
uuid = "${openstack_networking_network_v2.NET_1.id}"
}
}
Created three ports of same network and tried to add them in compute_instance:
resource "openstack_compute_instance_v2" "VM1" {
name = "VM1"
count = "1"
image_name = "image"
flavor_name = "flavor"
network = {
port = "${openstack_networking_port_v2.port_1.id}"
}
network = {
port = "${openstack_networking_port_v2.port_2.id}"
}
network = {
port = "${openstack_networking_port_v2.port_3.id}"
}
}
Unfortunately both did not work.
I am able to launch instance with single port.
Post creation I wanted to add additional interfaces.
Literally, I wanted to do the below post VM creation with single interface:
nova interface-attach --net-id $NET_1 "$VM1"
nova interface-attach --net-id $NET_1 "$VM1"
I did asp.net program using mvc 4. I deployed in iis server as localhost; I want track HTTP Packet so I used SharpPcap.
Here is full code...
namespace CaseStudy
{
class Program
{
static void Main(string[] args)
{
var parmenter = SharpPcap.CaptureDeviceList.Instance;
/*If no device exists, print error */
if (parmenter.Count < 1)
{
Console.WriteLine("No device found on this machine");
return;
}
int i = 0;
Console.WriteLine("Choose Your Devices :");
Console.WriteLine("----------------------");
foreach (PcapDevice dev in parmenter)
{
/* Device Description */
Console.WriteLine("{0}] {1} [MAC:{2}]", i, dev.Interface.FriendlyName, dev.Interface.MacAddress);
i++;
}
Console.WriteLine("----------------------");
//Extract a device from the list
int deviceIndex = -1;
do
{
Console.WriteLine("Enter Your Choice :");
deviceIndex = int.Parse(Console.ReadLine());
} while (!(deviceIndex < parmenter.Count && deviceIndex >= -1));
ICaptureDevice device = parmenter[deviceIndex];
//Register our handler function to the 'packet arrival' event
//device.PcapOnPacketArrival += new SharpPcap.PacketArrivalEventHandler();
device.OnPacketArrival += new SharpPcap.PacketArrivalEventHandler(device_OnPacketArrival);
//Open the device for capturing
//true -- means promiscuous mode
//1000 -- means a read wait of 1000ms
device.Open(DeviceMode.Promiscuous, 1000);
device.Filter = "ip and tcp";
Console.WriteLine("-- Listenning on {0}, hit 'Enter' to stop...", device.MacAddress);
//Start the capturing process
device.StartCapture();
//Wait for 'Enter' from the user.
Console.ReadLine();
//Stop the capturing process
device.StopCapture();
//Close the capturing device
device.Close();
}
private static void device_OnPacketArrival(object sender, CaptureEventArgs e)
{
DateTime time = e.Packet.Timeval.Date;
int len = e.Packet.Data.Length;
byte[] data = e.Packet.Data;
//var packet = TcpPacket.ParsePacket(e.Packet.LinkLayerType, e.Packet.Data);
//Console.WriteLine(e.Packet.LinkLayerType.ToString());
Packet pack = Packet.ParsePacket(e.Packet.LinkLayerType, e.Packet.Data);
if (pack is PacketDotNet.EthernetPacket)
{
var eth = pack.Extract(typeof(EthernetPacket)) as EthernetPacket;
if (len > 100)
{
Console.WriteLine("ETHERNET/INTERNET/HTTP PACKET");
//Console.WriteLine(HttpServerUtility.UrlTokenEncode(eth.Bytes));
Console.WriteLine("{0}-{1}" , eth.DestinationHwAddress, eth.SourceHwAddress);
//Console.WriteLine(eth.PayloadPacket.PayloadPacket.PrintHex());
Console.WriteLine(System.Text.Encoding.UTF8.GetString(eth.Bytes));
}
}
if (pack is PacketDotNet.TcpPacket) {
var tcp = pack.Extract (typeof(TcpPacket)) as TcpPacket;
if (len > 100)
{
//Console.WriteLine("[{0}:{1}:{2}:{3}][{4}][{5}]",
//time.Hour, time.Minute, time.Second, time.Millisecond,
//len, Stringfy.RawPacketToHex(data));
Console.WriteLine("TCP PACKET");
Console.WriteLine(tcp.PrintHex());
//Console.WriteLine(arp.SenderHardwareAddress);
}
}
if (pack is PacketDotNet.InternetPacket)
{
var inet = pack.Extract(typeof(InternetPacket)) as InternetPacket;
if (len > 100)
{
//Console.WriteLine("[{0}:{1}:{2}:{3}][{4}][{5}]",
//time.Hour, time.Minute, time.Second, time.Millisecond,
//len, Stringfy.RawPacketToHex(data));
Console.WriteLine("INTERNET PACKET");
Console.WriteLine(inet.PrintHex());
//Console.WriteLine(arp.SenderHardwareAddress);
}
}
if (pack is PacketDotNet.IpPacket)
{
var ip = pack.Extract(typeof(IpPacket)) as IpPacket;
if (len > 100)
{
//Console.WriteLine("[{0}:{1}:{2}:{3}][{4}][{5}]",
//time.Hour, time.Minute, time.Second, time.Millisecond,
//len, Stringfy.RawPacketToHex(data));
Console.WriteLine("IP PACKET");
Console.WriteLine(ip.PrintHex());
//Console.WriteLine(arp.SenderHardwareAddress);
}
}
}
}
}
this code caputuring remote server http packet like google, stackoverflow, facebook communicate with my system.
However i want track packet with my system only as a localhost.
using
any one can help? please...
It's impossible.
Why?
SharpPcap uses WinPcap and WinPcap extends the system driver to capture packets. According to WinPcap faq Question 13, it's not possible to capture the loopbackdevice aka localhost. It's a limitation of Windows not WinPcap.