从嵌套Hashmap中获取键和值



所以,我使用交换机ID为两个交换机创建一个嵌套哈希映射,然后放入源Mac地址和端口。

。switch1应该包含它自己的映射,switch2也应该包含它自己的映射,而且这两个交换机显然应该相互通信,因此我将HashMap设置为如下所示:

HashMap<String, HashMap<Long, Short>> map = new HashMap<String, HashMap<Long,Short>>();
if(sw.getId() == 1){
        switchMap.put("1", new HashMap<Long, Short>());
        switchMap.get("1").put(sourceMac, (short) pi.getInPort());
}
else if(sw.getId() == 2){
        switchMap.put("2", new HashMap<Long, Short>());
        switchMap.get("2").put(sourceMac, (short) pi.getInPort());
}

现在,我想做的是检查每个交换机的密钥(1或2),然后检查每个交换机在检查给定的目的地mac时是否有正确的源mac和端口#:

Long destinationMac = Ethernet.toLong(match.getDataLayerDestination());
if (switchMap.containsKey("1") && switchMap.containsValue(destinationMac)) {    
    /* Now we can retrieve the port number. This will be the port that we need to send the
    packet over to reach the host to which that MAC address belongs. */
    short destinationPort = (short) switchMap.get("1").get(destinationMac);
    /*Write the packet to a port, use the destination port we have just found.*/
    installFlowMod(sw, pi, match, destinationPort, 50, 100, cntx);
} 
else if (switchMap.containsKey("2") && switchMap.containsValue(destinationMac)) {   
    /* Now we can retrieve the port number. This will be the port that we need to send the
    packet over to reach the host to which that MAC address belongs. */
    short destinationPort = (short) switchMap.get("2").get(destinationMac)
    /*Write the packet to a port, use the destination port we have just found.*/
    installFlowMod(sw, pi, match, destinationPort, 50, 100, cntx);
}
else {
    log.debug("Destination MAC address unknown: flooding");
    writePacketToPort(sw, pi, OFPort.OFPP_FLOOD.getValue(), cntx);
}

当我运行代码并尝试从h1(switch1) ping到h3(switch2)时,我得到请求返回,但我仍然得到错误消息"Destination MAC address unknown: flooding"

我的问题是,我得到的值从嵌套HashMap正确吗?还是我的逻辑完全混乱了?

for(String s: map.keySet()){
    HashMap<Long, Short> switchMap =map.get(s);
    if(switchMap.containsValue(destinationMac)){ 
        return switchMap.get(destinationMac);
    }
}

您检查目的地址存在的方式是错误的。它应该是这样的:

Short portS1 = switchMap.get("1").get(destinationMac)
if (portS1 != null) {
  installFlowMod(sw, pi, match, portS1, 50, 100, cntx);
}
Short portS2 = switchMap.get("1").get(destinationMac)
if (portS2 != null) {
  installFlowMod(sw, pi, match, portS2, 50, 100, cntx);
}

要使其工作,您必须使用空Map<Long, Short>初始化所有交换机映射。

一个更通用的方法是:

for (Map.Entry<String, Map<Long, Short>> e: switchMap.entrySet()) {
  Short port = e.getValue().get(destinationMac);
  if (port != null) installFlowMod(sw, pi, match, port, 50, 100, cntx); 
}

这样做,你甚至不需要预先初始化switchMap

最新更新